arame3333
arame3333

Reputation: 10193

JQuery - cannot wire up the change event

In my MVC application I have a form and I make 2 asynchronous AJAX calls, 1 to get a new page of data, the other to display the results of a search. The intial load of the form prior to these calls is fine. I want to colour bar my rows, and this works;

$("#tblePagedList").on("change", styleRows);

function styleRows() {
    $("#tblePagedList tr:even").addClass("row1");
    $("#tblePagedList tr:odd").addClass("row2");
}

However these styles are not applied after I navigate to a new page or I make a search. My attempts to wire up a change event fail;

ie

$("#tblePagedList").on("change", styleRows);

or

$("#tblePagedList").change(styleRows);

My table looks like;

<table id="tblePagedList">
    <thead>
        <tr>
            <th>
                Company
            </th>
            <th>
                Address
            </th>
            <th style="width:100px;">
                Telephone
            </th>
            <th style="width:100px;">
                Contact
            </th>
            <th style="width:100px;">
                Trade
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody id="tblePagedListBody"></tbody>
    @foreach (var item in Model) {
        <tr>
            <td>
                @item.Company
            </td>
            <td>
                @item.AddressLine
            </td>
            <td>
                @item.Telephone
            </td>
            <td>
                @item.Contact
            </td>
            <td>
                @item.TradeName
            </td>
            <td>
                @Html.ActionLink("Details", "DetailsSubcontractor", new { id = item.CompanyId })
            </td>
        </tr>
    }

Upvotes: 0

Views: 64

Answers (1)

skalee
skalee

Reputation: 12675

On Change event is triggered when input's value changes, not when DOM is altered. If you need an event, I'd register a custom one, let's call it update:

`$("#tblePagedList").on("update", handler)`

and trigger it manually when AJAX call succeeds:

`$("#tblePagedList").trigger("update")`

But I'm not sure if you really need events. Perhaps calling styleRows in AJAX callback is enough?

And if you really like idea of events, consider switching to BackboneJS. You could store fetched data in collection, hook to collection update event and render table on that event.

BTW Two subsequent styleRows calls may give wrong results, remove old classes:

function styleRows() {
    $("#tblePagedList tr:even").removeClass("row1 row2").addClass("row1");
    $("#tblePagedList tr:odd").removeClass("row1 row2").addClass("row2");
}

Upvotes: 2

Related Questions