The records themselves are derived from mysql. It turns out the type code:

<tr><td>Запись 1</td><td><button id="delete" value="1">удалить</button></td></tr> <tr><td>Запись 2</td><td><button id="delete" value="2">удалить</button></td></tr> <tr><td>Запись 3</td><td><button id="delete" value="3">удалить</button></td></tr> 

need to implement removal. I attach the script code:

 $(document).ready (function() { $("#delete").bind("click", function() { $.ajax ({ url: "/user/delete", type: "POST", data: ({name: $("#delete").val()}), dataType: "html", beforeSend: function (){ $('#delete_spinner').html('<i class="fa fa-spinner fa-spin"></i>'); }, success:function(data){ alert(data) document.getElementById('delete_spinner' ).style.display = 'none'; document.getElementById('update' ).click(); } }); }); 

});

The problem is that it reads by clicking on id = "delete", and since there are a lot of them, it takes the first one, respectively, but deleting the first record works. How to make to delete any entry?

  • $(this).val() because you need to take. But as it is written in the answers, to identify the button it is better to make class="delete" id="1" , otherwise the identifier is not valid. - teran
  • and how to rewrite this line data: ({name: $ ("# delete"). val ()}) so that you can pass each value to the script. I know very little javascript, I don’t know how to write it down - Vadim Moroz
  • Duck, I wrote above and how. { name: $(this).val() } - teran
  • after that, you know that document.getElementById('delete_spinner' ).style.display = 'none'; can be written as $("#delete_spinner").toggle(false) or .hide() ? - teran
  • I knew about hide, no toggle. Thanks for prompting, I will comprehend JS. they helped a lot, I really wrote a little differently, via id data: ({name: $ (this) .attr ("id")}), but your version is more understandable - Vadim Moroz

3 answers 3

ID is a unique parameter. You can not use the same ID for different elements.
To solve the problem, use the class and read the value of this element or the data-attribute in the handler per click.

    According to the W3C specification, this is not valid.

    Try replacing all the elements with IDs by classes, or replace the selector with the following:

     $('[id="delete"]'); 

      Use! Customize

      Add to item

       onclick="javascript:del(тут id);" 

      Code

       function del(id){ jQuery.ajax({ type: "post", url: "/delete_ajax.php", data: "id=" + id + "&vid=lids", dataType: 'json', success: function(data){ if(data.succes == 0){ jQuery('#msg').html('' + data.msg + '').delay(3000).fadeOut('fast'); } if(data.succes == 1){ $('li[data-lidid=' + data.lidid + ']').animate({ bottom:"+=30%",opacity:0 }, "slow", function(){jQuery(this).hide();}); // удаляем удаленный элемент } } }); } 
      • What is the meaning of this half of the classic JS which should be searched somewhere in the text of the page, and half of the jQuery? - teran