javascript - Sum the contents of many dropdowns when any of them change -
i have several dropdowns on page, , contain numbers. when user change 1 of these, need go through of them , sum numbers.
how jquery?
<select id="number1"> <option value="1">1</option> <option value="3">3</option> </select> <select id="number2"> <option value="1">1</option> <option value="3">3</option> </select> <select id="number4"> <option value="1">1</option> <option value="3">3</option> </select>
i've tried like:
$('select[id*="number"].change(function() { // when 1 dropdown change $('select[id*="number"].change(function() { // go through them var current = $(this); // add current value array }); }); $.each(arr,function() { total += this; // sum items });
but doesn't quite work expected. tips? thanks.
you seem trying nest calls change()
inside each other. don't use change()
second time, use .each()
. (also missing closing ')
@ end of each of selectors code wouldn't work @ all.)
it doesn't make sense loop through array outside change()
handler, because when code run?
try this:
$('select[id*="number"]').change(function() { // when 1 dropdown change total = 0; // reset total $('select[id*="number"]').each(function() { // go through them total += +this.value; // use unary plus convert string value addition }); // total here });
Comments
Post a Comment