dangerChihuahua007
dangerChihuahua007

Reputation: 20925

Why is jQuery not detecting dynamically loaded jQuery Mobile buttons?

I loaded the following HTML via Ajax into a web page powered by jQuery Mobile. What's important is the class name of onButton attached to the anchor tag.

<a class="onButton ui-btn ui-btn-inline ui-btn-corner-all ui-shadow ui-btn-up-c" href="#" data-role="button" data-inline="true" data-theme="c"><span class="ui-btn-inner ui-btn-corner-all"><span class="ui-btn-text">Turn On</span></span></a>

After loading via Ajax, I triggered a "create event" to apply jQuery Mobile button styles per the documentation.

$.ajax({
    url: '/loadAllButtons',
    context: $('contentBox'),
    cache: false,
    data: {'listOfEntities': JSON.stringify([1,2,3,4,5])},
    success: function(data) {
        $(this).html(data).trigger( "create" );
    }
});

I see that the buttons have been successfully loaded. However, when I call console.log($('.onButton').length);, the console displays 0.

That is interesting because Chrome Web Developer notes 5 instances of <a> tags with the onButton class loaded via Ajax.

Why is jQuery not detecting the newly loaded anchor tags (or buttons)?


To be clear, here is how I am debugging:

$.ajax({
    url: '/loadAllButtons',
    context: $('contentBox'),
    cache: false,
    data: {'listOfEntities': JSON.stringify([1,2,3,4,5])},
    success: function(data) {
        $(this).html(data).trigger( "create" );
    }
});
console.log($('.onButton').length);

Thank you.

Upvotes: 1

Views: 460

Answers (1)

Jasper
Jasper

Reputation: 76003

You need to put your debugging console.log() in the callback for the AJAX call. As it is, the console.log() is running just after the request is sent (since by default AJAX requests are asynchronous), which will be before the response is received from the server and therefore before any elements have been added to the DOM.

Try this:

$.ajax({
    url: '/loadAllButtons',
    context: $('contentBox'),
    cache: false,
    data: {'listOfEntities': JSON.stringify([1,2,3,4,5])},
    success: function(data) {
        $(this).html(data).trigger( "create" );
        console.log($('.onButton').length);
    }
});

Also, since you are adding button elements to the DOM that already have the jQuery Mobile classes/structure applied, you may need to call .button('refresh') to refresh the elements instead of .trigger('create') to initialize them. I haven't used .button('refresh') before so I'm not sure if you can call it on an ancestor element of the buttons or if you have to call it on the buttons themselves like:

$(this).html(data).find('.onButton').button( "refresh" );

Upvotes: 1

Related Questions