pomeKRANK
pomeKRANK

Reputation: 47

(JQuery) modify array

I have this code where a table is made from an array (myList) and you can delete a specific row and the table will rebuilt itself with the new list. This works fine for the first time on my computer (but not on the snippet), but when you try again, it just doesn't work.

$( document ).ready(function() {
    createTable(myList, myList.length);
});

$('.btn').click( function(){
  var rowOn = $(this).closest("tr").index();
	myList.splice(rowOn, 1);
	createTable(myList, myList.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id = "myTab">
  <thead><tr><td>col1</td><td>col2</td></tr></thead>
  <tbody>
  </tbody>
</table>

<script>
var myList = ["a", "b", "c", "d", "e"];
createTable = function(list, nb){
  $('#myTab > tbody > tr').remove();
  for (var i = 0; i < nb; i++) {
    var str = '<td><button class="btn">Delete</button></td>';
    $('#myTab > tbody').append('<tr>'+str+'<td>'+list[i]+'</td></tr>');
  }
};
</script>

PS: this is a simplified sample of the code, I really need to rebuild the entire table in my case so just hidding the row will not work.

Thanks!

Upvotes: 1

Views: 27

Answers (1)

eisbehr
eisbehr

Reputation: 12452

You need to create a dynamic event delegation, because you recreate your buttons and so your listeners get lost otherwise when recreateing the table.

$('table').on('click', '.btn', function() { /* ... */ });

var myList = ["a", "b", "c", "d", "e"];

function createTable(list, nb){
    $('#myTab > tbody > tr').remove();

    for (var i = 0; i < nb; i++) {
        var str = '<td><button class="btn">Delete</button></td>';
        $('#myTab > tbody').append('<tr>'+str+'<td>'+list[i]+'</td></tr>');
    }
};

$(function() {
    createTable(myList, myList.length);
});

$('table').on('click', '.btn', function() {
    var rowOn = $(this).closest("tr").index();
    myList.splice(rowOn, 1);
    createTable(myList, myList.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id = "myTab">
  <thead><tr><td>col1</td><td>col2</td></tr></thead>
  <tbody>
  </tbody>
</table>

Beside this, why do you want to recreate the table every time? You could only remove the clicked row.

var myList = ["a", "b", "c", "d", "e"];

$(function() {
    $('#myTab > tbody > tr').remove();

    for (var i = 0; i < myList.length; i++) {
        var str = '<td><button class="btn">Delete</button></td>';
        $('#myTab > tbody').append('<tr>'+str+'<td>'+myList[i]+'</td></tr>');
    }
});

$('table').on('click', '.btn', function() {
    var row = $(this).closest("tr");
    myList.splice(row.index(), 1);
    row.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id = "myTab">
  <thead><tr><td>col1</td><td>col2</td></tr></thead>
  <tbody>
  </tbody>
</table>

Upvotes: 1

Related Questions