Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's another variant, which also does some simple parsing in case you have <code>100g</code> as input, versus <code>100</code>. Also, the data structure gets reinitialized every time, so everything does not get doubled on every click.</p> <pre><code>$(".calculate").bind("click", function(e) { //get the correct parent of the button var parent = $(this).closest("#calc"); var ingredients = {}; var extractWeight = function (input) { // you can add other logic here // to parse stuff like "1kg" or "3mg" // this assumes that everything is // in grams and returns just the numeric // value return parseInt(input.substring(0, input.length - 1)); } //get relevant data parent.find(".options").each(function(index, element) { var opt1 = $(this).children(".opt1").children("input").val(); //weight var opt2 = $(this).children(".opt2").children("input").val(); //ingredient // initialize to 0 if not already initialized ingredients[opt2] = ingredients[opt2] ? ingredients[opt2] : 0; ingredients[opt2] += extractWeight(opt1); }); });​ </code></pre> <p>Here are some tips:</p> <ul> <li><code>{}</code> is called an object literal and is used to create a new empty object</li> <li>object members can be accessed dynamically through the <code>[]</code> notation (i.e. if <code>x === "name"</code> then <code>o[x] === o.name</code>)</li> <li>variables are visible inside functions that are at the same level or deeper in the scope - like in my example I use <code>ingredients</code> in the <code>each</code> function.</li> <li>arrays in JavaScript only support numeric keys, so you won't have stuff like PHP's "associative arrays". Objects fill this gap in JS.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload