I want to populate a table using jQuery. I have an array of strings and when I click a button to run a function, I'd like to use that array to populate the table. The first time I click the button, it works perfectly, but when I call the function a second time, the rows are duplicated :/ (The table is not reset)
My html code:
<table id="tableIdentity" class="table table-striped">
<tr>
<th>name</th>
</tr>
</table>
<button type="button" onclick="loadTable();">load table</button>
My js function:
function loadTable() {
var data = ['allan','ronaldo','damian'];
for(var i = 0; i<data.length; i++) {
var row = '<tr><td>'+data[i]+'</td></tr>';
$('#tableIdentity').append(row);
}
}
You can add a class and remove it when you click
function loadTable() {
var data = ['allan','ronaldo','damian'];
$('#tableIdentity .append_class').remove();
for(var i = 0; i<data.length; i++) {
var row = '<tr class="append_class"><td>'+data[i]+'</td></tr>';
$('#tableIdentity').append(row);
}
}