Page 1 of 1

jQuery - Append rows in table then hide the button

Posted: 11 Jan 2015, 08:31
by MarPlo
I have a html table and a button, like this:

Code: Select all

<table id="tb_id" border="1">
  <tr>
    <th>Website</th>
    <th>Title</th>
    <th>Description</th>
  </tr>
  <tr>
    <td>https://coursesweb.net/</td>
    <td>Web programming & development</td>
    <td>Description for CoursesWeb.net</td>
  </tr>
</table>
<button id="btn1">Append Row</button>
And a JavaScript array with rows data that I want to add in the html table, one by one, when the button #btn1 is pressed.

Code: Select all

// array with table rows to append
var trows = [
  '<td>http://www.marplo.net/</td><td>Free courses and Flash Games</td><td>Description for MarPlo.net</td>',
  '<td>http://www.php.net/</td><td>PHP Programming</td><td>Description for PHP.net</td>'
];
Then, to hide the button when the last item with row data is added.
How can I do this with jQuery: to append a row in a html table when a button is pressed, then to hide that button?

jQuery - Append rows in table then hide the button

Posted: 11 Jan 2015, 08:40
by Admin
To append a row in a html table, use this syntax:

Code: Select all

$('#table_id > tbody:last').append('<tr>...</tr>');
And to hide the pressed button:

Code: Select all

$(this).hide('slow');
Here's the code that appends rows in your html table and hides the button after the last row is added:

Code: Select all

<table id="tb_id" border="1">
  <tr>
    <th>Website</th>
    <th>Title</th>
    <th>Description</th>
  </tr>
  <tr>
    <td>https://coursesweb.net/</td>
    <td>Web programming & development</td>
    <td>Description for CoursesWeb.net</td>
  </tr>
</table>
<button id="btn1">Append Row</button>

<script>
// array with table rows to append
var trows = [
  '<td>http://www.marplo.net/</td><td>Free courses and Flash Games</td><td>Description for MarPlo.net</td>',
  '<td>http://www.php.net/</td><td>PHP Programming</td><td>Description for PHP.net</td>'
];
var ir = 0;

// append LI in #lists
$('#btn1').click(function(){
  $('#tb_id > tbody:last').append('<tr>'+ trows[ir] +'</tr>');  // append current "ir" row
  ir++;
  if(ir == trows.length) $(this).hide('slow');  // if last row to append, hides the button
});
</script>