JohnC1
JohnC1

Reputation: 861

On Click event not working after loading element through Ajax call

I am loading the page (contains the javascript), and then I am loading the PartialView (contains the table). The problem is, I can't select the table id or the onClick event does not fire.

Index.cshtml

$('#sortingRow').on('click', 'th a', function () {
    $.ajax({
        url: this.href,
        type: 'GET',
        data: { sortOrder: sortOrder },
        success: function (result) {
            $('#sortingRow').parent().html(result);
            LoadSampleDesign();
        }
    });
    return false;
});

_PartialView.cshtml

<table>
    <tr id="sortingRow">
        <th>
            <a href="link">Click Me</a>
        </th>
    </tr>
</table>

That partialView is being loaded using Ajax, like this:

$(sections).on('click', '#sectionPageLinks a', function () {
    $.ajax({
        url: this.href,
        type: 'GET',
        success: function (result) {
            $('#sectionPageLinks').parent().html(result);
            LoadSampleDesign();
        }
    });
    return false;
});

I've tried JsFiddle and the javascript seems to be working correctly. Also, At first, you might think the problem is that jquery couldn't find the table since it was being loaded after DOM completed, but that's why I'm using "on()", doesn't that make it live so it should be able to find the #table even after DOM was completed.

Upvotes: 0

Views: 1431

Answers (1)

Praveen Reddy
Praveen Reddy

Reputation: 7393

After loading the partial view via Ajax the click event is no longer bound. Change your row click event as follows.

$('#sortingRow').on('click', 'th a', function () {

$(document).on('click', '#sortingRow th a', function () {

Upvotes: 1

Related Questions