You probably want to add some class
and/or id
attributes to your inputs so that this code will play nicely if dropped into a larger HTML context. However, to answer the question as given:
$("input[type=text]").blur(function() {
var sum = 0;
$("input[type=text]").each(function () { // For each of the two inputs
sum += parseInt($(this).val()) // ... add its value to sum
});
$("div.sum").text(sum); // Update the div
});
If you're entering numbers with a decimal point, you'll probably want to use parseFloat
rather than parseInt
.
UPDATE: If your structures are all like the one posted, the easiest way to relate them to one another would be to use an id
attribute on the containing table, and the descendant selector syntax. Then the code would look like this:
$("input[type=text]").blur(function() {
var parentId = $(this).parents('table').attr('id');
var sum = 0;
$(parentId +" input[type=text]").each(function () {
sum += parseInt($(this).val())
});
$(parentdId + " div.sum").text(sum);
});
UPDATE AGAIN: Okay, so you have no way to assign ids to your tables. That's okay, we can still get this done. You'll have to use jQuery's traversal functions parent()
and find()
instead of simple selectors, that's all.
$("input[type=text]").blur(function() {
var parent = $(this).parents('table');
var sum = 0;
parent.find("input[type=text]").each(function () {
sum += parseInt($(this).val())
});
parent.find("div.sum").text(sum);
});