-2

How can I add rows to a table with this structure using Javascript?

Basically I want to be able to click a button and have a new row created within the table for each of the columns used below. So for instance, it could be name: new book, quantity:30 etc.

<table id="dynamictable">
    <tbody>
        <tr>
            <td class="name">My Favorite book</td>
            <td class="quantity">x&nbsp;20</td>
            <td class="unit_price">£8.99</td>
            <td class="total">£179.80</td>
            <td class="remove">
                <img src="image/cross.png">
            </td>
        </tr>
    </tbody>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2132159
  • 33
  • 1
  • 4
  • 10
    [What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please. – John Conde Mar 04 '13 at 14:44
  • 2
    have you heard about clone()? Learn about it. – epascarello Mar 04 '13 at 14:47
  • I have always had good results with [JQuery-tmpl](https://github.com/jquery/jquery-tmpl), however it seems it is no longer maintained - works well still though – musefan Mar 04 '13 at 14:48
  • look at [this](http://stackoverflow.com/questions/595808/is-it-possible-to-append-to-innerhtml-without-destroying-descendants-onclick-fu) – j0hnstew Mar 04 '13 at 14:48

2 Answers2

0
var newRow = '<tr><td class="name">New Book</td>[...]</tr>'; // add all your code here
$('#dynamictable tbody').append(newRow);

should do it (untested).

acme
  • 14,654
  • 7
  • 75
  • 109
0

Clone the first row on button click. Fill in the new data. Then append it to the table.

$( '#mybutton' ).click(function(){
    var tr = $('#dynamictable tr').eq(0).clone();

    tr.find('td').each(function(){
        $(this).html( 'Put Your Data Here.' );
    });

    $('#dynamictable').append(tr);


});

jsFiddle: http://jsfiddle.net/4hrVQ/1/

Jesse Lee
  • 1,291
  • 1
  • 8
  • 20
  • That adds the same information under each heading. I want to be able to add Name: Fantasy Quantity:30 Unit_Price:2.30 Etc. How do I do that with the above code – user2132159 Mar 04 '13 at 15:44
  • 1
    That depends on your data source. What does the data source look like? – Jesse Lee Mar 05 '13 at 02:02