How to catch onchange event on multiple textbox field
HTML code:
开发者_如何学Go<input type="text" name="percentage[]" value="1"/>
<input type="text" name="percentage[]" value="2"/>
<input type="text" name="percentage[]" value="3"/>
I want to be able to catch change event by using JQuery when any of the 'percentage' text fields changes and find sum of all these fields. So, if the value on the first field changes from 1 to 5, I want to be able to display "10".
You can also use something like this:
$("input[type='text'][name^='percentage']").keyup(function(){
alert(sumThemUp());
});
function sumThemUp(){
var sum = 0;
$("input[type='text'][name^='percentage']").each(function(){
sum+= parseInt($(this).val());
});
return sum;
};
Working example at jsfiddle.
You can also check jQuery API to choose selector that might fit you better if you wish. There are many variations like !=, ~=, *= etc.
Assuming you have another element to show the sum in, and no other input elements, this will work:
$("input[type=text]").change(function() {
// Clear the sum
$("#sum").text("0");
// Sum the values
$("input[type=text]").each(function() {
$("#sum").text( parseInt($("#sum").text()) + parseInt($(this).val()))
});
});
It catches the elements changing, and then loops over all of them and sums them up.
精彩评论