1

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

1
  • Have you tried anything? You should have... Commented Apr 26, 2011 at 14:17

2 Answers 2

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());
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.