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 }); 

demo: http://jsfiddle.net/nnnnnn/8l9hz/


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -