jquery performing calculation on dynamically generated elements

Posted by user306472 on Stack Overflow See other posts from Stack Overflow or by user306472
Published on 2010-04-05T21:17:38Z Indexed on 2010/04/05 21:23 UTC
Read the original article Hit count: 363

I have a table made up of a row of 3 input elements: Price, Quanity, and Total. Under that, I have two links I can click to dynamically generate another row in the table. All that is working well, but actually calculating a value for the total element is giving me trouble. I know how to calculate the value of the first total element but I'm having trouble extending this functionality when I add a new row to the table. Here's the html:

<table id="table" border="0">
    <thead>
        <th>Price</th><th>Quantity</th><th>Total</th>
    </thead>
<tbody>
<tr>
    <td><input id ="price" type = "text"></input></td>
    <td><input id ="quantity" type = "text"></input></td>
    <td><input id ="total" type = "text"></input></td>
</tr>
</tbody>
</table>
<a href="#" id="add">Add New</a>
<a href="#" id="remove">Remove</a>

Here's the jquery I'm using:

$(function(){
  $('a#add').click(function(){
    $('#table > tbody').append('<tr><td><input id ="price" type = "text"></input></td><td><input id ="quantity" type = "text"></input></td><td><input id ="total" type = "text"></input></td></tr>');  
   });
  $('a#remove').click(function(){
  $('#table > tbody > tr:last').remove();
  });
});

$(function(){
    $('a#calc').click(function(){
    var q = $('input#quantity').val();
    var p = $('input#price').val();
    var tot = (q*p);
    $('input#total').val(tot);
    });
 });

I'm new to jquery so there's probably a simple method I don't know about that selects the relevant fields I want to calculate. Any guidance would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about calculation