count the textbox values using javascript
I have dynamically added rows using javascript.now I have to sum the values in the text boxes.if i click add button the same row will be added.now i have one fixed textbox.开发者_运维技巧if i enter the values in the textbox it should add and get displayed in the fixed textbox on keypress.how can i do this with javascript or jquery
here is my html and jquery scripts to addd the row
input id="name" type="text" input id="add" type="button" value="+" input id="Button1" type="button" onclick="removeRowFromTable();" value="x"
I have used jquery to add the rows dynamically and javascript to delete the rows
$(document).ready(function()
{
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});
return false;
return false;
});
});
function removeRowFromTable() { var tbl = document.getElementById('mytable'); var lastRow = tbl.rows.length; if (lastRow > 2) tbl.deleteRow(lastRow - 1); }
Here is a quick plugin I've written using jQuery.
$.fn.sum = function(settings) {
settings = jQuery.extend({
name: "sum",
global: true
}, settings);
var total = 0.0;
this.each(function() {
var item = parseFloat($(this).val());
if (isNaN(item)) item = 0;
total += item;
});
return total;
};
Then to wire up your add button
$('.add').click(function() {
$('.total').html($('.rowTotal').sum());
});
Provided you are adding rows with a predictable naming scheme, you simply iterate over the controls, find the textboxes and make sure the name fits your scheme. Since this is an "add the numbers" function, you also want to attach a function that will not allow anything but numbers in the box, or you will error out.
If the naming is not predictable, and/or you are only using textboxes for the numbers, you can simplify by finding all controls that are textboxes.
精彩评论