I'm trying to return the sum of values every time one of the select is changed. But the sum is always wrong:
$('select').change(function () {
a = 0;
$('select').each(function () {
a += parseInt($('option:selected').val(), 10);
});
$('h1 span').html(a);
});
http://jsfiddle.net/vAu3E/
$('select').change(function () {
var a = 0;
$('select').each(function () {
a += parseInt(this[this.selectedIndex].value, 10);
});
$('h1 span').html(a);
});
Use this.value (faster than re-getting a jQuery object when you already have it) and declare a so it's not global (I also invoked the handler immediately so your result shows immediately):
$('select').change(function () {
var a = 0;
$('select').each(function () {
a += parseInt(this[this.selectedIndex].value, 10); //originally this.value
});
$('h1 span').html(a);
}).change();
http://jsfiddle.net/vAu3E/10/
See comments for potential issues with this.value in versions of IE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With