In general, there is a page where I work with ajax and jquery. On one half of the page there are 3 inputa where I drive the info, the second one contains the table where the previously entered information falls, that is, the table is dynamically generated.

The data entered in the input is sent by the Ajax to the PCP handler, which in turn pushes them into the database, and then forms a json file from the database (Do not ask why I am doing so, this is by condition). Then, with an Ajax, I read the json file and put it into a table on the page.

In general, here's the code:

<script type="text/javascript"> $(document).ready(function(){ //Тут я по клику собираю данные $("#send").click(function() { //из инпутов и отправляю в обработчик var firstName = $('#firstName').val(); var secondName = $('#secondName').val(); var email = $('#email').val(); $.ajax({ url: "core.php", type: "POST", data: {firstName,secondName,email} }); }); $.ajax({ //Тут я беру готовый json файл и вывожу url:"table_push.json", //в таблицу на странице dataType: "json", success:function() { $.getJSON('table_push.json',function (data) { for(var i = 0; i<data.length;i++){ $('#users').append('<tr><td>' + data[i].id + '</td><td>' + data[i].firstName + '</td><td>' + data[i].secondName + '</td><td>'+ data[i].email+'</td><td><button id='+data[i].id+' class="btn btn-danger">Remove</button></td></tr>'); } // В цикле сверху, я присваиваю id тегу <button>, $(".btn").bind('click', function () { // что б было var line = $(this).attr('id'); // удобно удалить alert(line); //строку из таблицы // а вот в этой функции сверху я проверяю через алерт })//правильность присвоенного id кнопке, выводит }); $(".btn").bind('click', function () { var line = $(this).attr('id'); alert(line); // а вот в этой функции я уже не могу обратится к id }) // на странице ничего не происходит и ошибок в консоли нету // по этому не могу напсать ещё один ajax запрос на удаление // данных из таблицы в БД } }); }); </script> 

The task is to bring information to the table, and then delete it by clicking on a specific entry in the table. But I can not do this, because I can not turn on the id to the record that needs to be deleted. If you look through the console in the browser, then all the buttons for deleting the entry are assigned id, but I can’t access them to manipulate the contents of the table in the future.

    2 answers 2

    1. Instead of id use data- * attributes

    In HTML5, for any element you can use your own attributes, starting with the prefix data-. This allows you to store information without occupying the standard attributes that carry other functionality.

    Create a button like this:

     <button data-id=' + data[i].id + ' class="btn btn-danger">Remove</button> 

    Then in the script, get the id using data () :

     var line = $(this).data('id'); 
    1. Use closest ()

    To find the row of the table in which the button is located, it is not necessary to give it a unique name:

     $(this).closest('tr').remove() 
    1. Give row id of the table according to the principle of TR+ID

    Let <tr> get id='tr'+data[i].id . Then you can easily get the id line, knowing the button id:

     var line = $(this).attr('id'); $('#tr'+line).remove() 

    Working example with closest ():

     var data=[ {firstName:'Foo', secondName:'Bar', email:'foo@Bar.ru',id:'1'}, {firstName:'Foo2',secondName:'Bar2',email:'foo@Bar.ru',id:'2'} ] for (var i = 0; i < data.length; i++) { $('#users').append('<tr><td>' + data[i].id + '</td><td>' + data[i].firstName + '</td><td>' + data[i].secondName + '</td><td>' + data[i].email + '</td><td><button id=' + data[i].id + ' class="btn btn-danger">Remove</button></td></tr>'); } $(".btn").bind('click', function() { var line = $(this).attr('id'); //здесь код удаления строки из БД $(this).closest('tr').remove() }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id=users></table> 

    Working example with data ():

     var data=[ {firstName:'Foo', secondName:'Bar', email:'foo@Bar.ru',id:'1'}, {firstName:'Foo2',secondName:'Bar2',email:'foo@Bar.ru',id:'2'} ] for (var i = 0; i < data.length; i++) { $('#users').append('<tr id=' + data[i].id + '><td>' + data[i].id + '</td><td>' + data[i].firstName + '</td><td>' + data[i].secondName + '</td><td>' + data[i].email + '</td><td><button data-id=' + data[i].id + ' class="btn btn-danger">Remove</button></td></tr>'); } $(".btn").bind('click', function() { var line = $(this).data('id'); //здесь код удаления строки из БД $('#'+line).remove() }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id=users></table> 

      Recheck the selector required. A little contradicts the statement, in the DOM you try to get class by code, not id.

      I assume that you have a problem in that the handler binds to elements that do not already exist on the page (not added to the DOM). After data is received from the server, and new elements are added to the page, click events are not attached to new ".btn" elements:

       $(".btn").bind('click', function () { var line = $(this).attr('id'); alert(line); }); 

      This code can be inserted inside the ajax event handler after the code that adds new elements to the DOM page. And you can use the following design:

       $(document).on('click', '.btn', function () { //Your code }); 

      Detailed information about the proposed construction by me, see the official documentation version of jQuery that you use. Or, here, here there is useful information: http://jquery.page2page.ru/index.php5/On