claudios claudios - 1 year ago 88
jQuery Question

jQuery selector to handle click function inside a loop result

Sorry for asking this again but code won't execute. The problem is that I have a php loop that produces a html like below

<a class="js-delete-comment1" data-url="http://localhost/project/document_items/delete_item_comment/1">link</a>
<a class="js-delete-comment2" data-url="http://localhost/project/document_items/delete_item_comment/2">link</a>
<a class="js-delete-comment3" data-url="http://localhost/project/document_items/delete_item_comment/3">link</a>

Now, I want to select specific class to use as a jQuery selector but won't work. See below code


var url = $('.js-delete-comment').attr('data-url');
// var id = $('.js-delete-comment').attr('data-id');
url : url,
type : 'POST',
dataType : 'json',
success : function(result) {

Any help would be much appreciated!

Answer Source

There is no ID on the elements, use class^= selector. There is no need of iterating over the elements and then bind the event, the event can be bind directly on the selector itself.

$("[class^='js-delete-comment']").click(function() {

Also, use $(this).data('url') to get the data-url attribute of the element that is clicked.


$("[class^='js-delete-comment']").click(function (e) {
    e.preventDefault(); // To stop page redirection

    var url = $(this).data('url');

        url: url,
        type: 'POST',
        dataType: 'json',
        success: function (result) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download