user794846
user794846

Reputation: 1931

jquery code not working after ajax refresh

I am using the following code to make the text red in any span with the class code and which contains text 'Failed to send invite'. This works however the table is part of pagination results set and the pagination is updated via ajax so when they change the page of results the red color is lost.

How do I make this code work in way the will work with the ajax content.

//This works for setting red in the initial page load   
$('table span.code').each( function() {
    if( /(Failed to send invite)/.test($(this).html())) {
        $(this).css('color', 'red');
    }
});

Upvotes: 1

Views: 545

Answers (2)

Jamie Taylor
Jamie Taylor

Reputation: 4775

Have you tried including this code when the new content is written to the page? jQuery doesn't work with live updates to the page, it runs once (unless you tell it otherwise).

You could always turn this into a function and just run the function every time you needed to loop through your table.

Upvotes: 2

Sergio
Sergio

Reputation: 6948

You have to rebind event handlers after ajax request refreshes part of a page:

$().ready(function () {
    bindHandlers();

    function doAjaxCall() {
        $.ajax({
            ...some codes,
            success: function (result) {
                ...some codes
                bindHandlers();
            }
        });
    }

    function bindHandlers() {
        $('table span.code').each( function() {
            if( /(Failed to send invite)/.test($(this).html())) {
                $(this).css('color', 'red');
            }
        });
    }
});

Upvotes: 0

Related Questions