Steve Steve - 4 months ago 7
jQuery Question

Appending a new row in the table

I have the two input fields.

<label>First Name:</label><input type="name" class="form-control" id="fname">
<label>Last Name:</label><input type="name" class="form-control" id="lname">
<button class="btn btn-primary" id="add">Add</button>


I am trying to add the values to the table. With every time i click add button i need to insert values in new row:

<table class="table bordered" id="table">
<thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td></tr></thead>
<tbody id="tbody">
<tr id="tr">
<td></td>
<td>
<div id="showf"></div>
</td>
<td>
<div id="showl"></div>
</td>
</tr>
</tbody>
</table>


This is what i have done. Jquery:

$(document).on('click', '#add', function (e)
{
e.preventDefault();
var fname=$('#fname').val();
var lname=$('#lname').val();

$('#tbody').append($('#tr').html());
$('#showf').append(fname);
$('#showl').append(lname);


});


the result is ok for the first column. And then next time i click on add button, the new row appears to be displaced

Answer

You should append the entire tr.

This should be your html:

<table class="table bordered" id="table">
   <thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td></tr></thead>
        <tbody id="tbody">

        </tbody>
</table>

And your Jquery should be:

$(document).on('click', '#add', function (e) 
{ 
    e.preventDefault();
    var fname=$('#fname').val();
    var lname=$('#lname').val();

    $('#tbody').append('<tr><td>' + fname + '</td><td>' + lname + '</td></tr>');
});
Comments