mariobgr mariobgr - 5 months ago 6
Javascript Question

foreach input multidimentional array

I have the following html

<input type="checkbox" name="array[0][count]" value="1"/>
<input type="hidden" data-price="50" name="array[0][id]" value="1"/>

<input type="checkbox" name="array[1][count]" value="5"/>
<input type="hidden" data-price="20" name="array[1][id]" value="2"/>


I want to calculate the sum of
using jQuery with the formula

foreach extra {
price += extra[id][data-price] * extra[count]

//not actual code, just a representation of the result needed

So far I was able to collect all the inputs using

$('input[name^="array"]').each(function() {

But I have no idea how to proceed further. Any help appreciated. If you can point me to a better way to structure the html array, I'm ok with that.


You are very close. All you need to do is get the price from the attribute now.


I noticed not all 'input[name^="array"]' have data attribute, so you need to check if it exists before adding or just rename the ones with the actual data attribute.

Below code works fine

$('input[name^="array"]').each(function() {

var dPrice =$(this).attr("data-price");
if(dPrice){ //check if data-price exists for the input
  price+= parseInt($(this).attr("data-price"),10);

Here's a working fiddle

Once you have the attribute, apply your formula and voila! You're done

UPDATE from comments:

While creating the checkbox from array, you do something like

<input type="hidden" data-price="50" name="array[0][id]" data-quantity=[count] value="1"/>

and then use the above code and get the data-quantity attribute and use it in your formula