llanato
llanato

Reputation: 2491

Jquery Event Delegation Issue

Can anyone suggest where I'm going wrong here? news_active is a static div, everything else is loaded in via ajax calls, nothing is being triggered for the alert, pretty stumped?!

$('#news_active').load('ajax.php', function() {
    // Delete news active
    $('#news_delete').on('click', function() {
        var vNid = $('#news_delete').attr('data-nid').val();
        alert(vNid);
        //$('#news_active').load('ajax.php?nid='+vNid);
    });
});

The button looks like this, there are multiple buttons loaded in with different data-nid values:

<button id="news_delete" data-nid="1">Delete</button>

Upvotes: 1

Views: 60

Answers (3)

palaѕн
palaѕн

Reputation: 73896

Since the news_delete is loaded dynamically, you need to use event delegation to register the event handler like:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#news_active').on('click', '#news_delete', function(event) {
    var vNid = $('#news_delete').data('nid');
    alert(vNid); 
});

Also, the way of getting the data-nid attribute value in your code is not correct.

Either use this:

var vNid = $('#news_delete').attr('data-nid');  // No need of .val() here
alert(vNid);

or just this using .data()

var vNid = $('#news_delete').data('nid');  
alert(vNid);

Upvotes: 2

Praveen
Praveen

Reputation: 56511

var vNid = $('#news_delete').attr('data-nid').val(); //remove the value it 
                                              // will return the value of button

change it to

var vNid = $('#news_delete').attr('data-nid');

Upvotes: 0

antyrat
antyrat

Reputation: 27765

You should use data() method instead:

var vNid = $('#news_delete').data('nid');

or just attr('data-nid') without val().

val() is trying to get Element.value property and you don't have it in button.

Upvotes: 2

Related Questions