Pedro Nunes
Pedro Nunes

Reputation: 1

jquery append content not trigering selector

I want to add a new row to a table using append by clicking on a image. I use ajax and php to retrieve the new row. After the row is appended the selector onchange does not trigger. Only for the first row.

I checked on Firebug and there is no event on the <select>

How can I make the second row to be triggered on the on change event ?

Code HTML:

<table id="tablines">
    <tr>
        <td>
            <select class="prod" data-id="1" name="product">
                <option value="a">A</option>
                <option value="b">B</option>
            </select>
        </td>
    </tr>
</table>
<img id="add" src="img/add1.png" style="cursor:pointer">

Code JQuery:

$('.prod').on( "change", function(){
    var dataid = $(this).data('id');
    alert (dataid);
});

$("img").click(function() {
    $.ajax  ({
        type: "GET",
        url: "getrow.php",
        success: function(data) {
            $('#tablines tbody').append(data);
            },
        });
});

The PHP return code is:

<tr>
    <td>
        <select class="prod" data-id="2" name="product">
            <option value="a">A</option>
            <option value="b">B</option>
        </select>
    </td>
</tr>

Upvotes: 0

Views: 57

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

delegate is preferably replaced by a delegated on call in later jQuery versions. This is the preferred version:

$(document).on("change", ".prod", function() {
  var dataid = $(this).data('id');
  alert (dataid);
});

It works by listening for the event to bubble up to a non-changing ancestor element. document is the best default if nothing else is closer/convenient. Do not use body as it has a bug.

It then applies the jQuery selector to only the elements in the bubble chain. It then executes the function for each matching element that caused the event.

The upshot of this is that it works on items added long after the event was registered

Upvotes: 1

urvish
urvish

Reputation: 27

1. please try after remove tbody from "$('#tablines tbody').append(data);"

or 2.

may be the easy way that you provide dynamic control id in jquery function so that particular raw can bind it...the same event(on change).

by $("#"+data-id).on("change",func....

and for that you have to add dynamic id to each raw append in your table. you can search for that on google.

Upvotes: 0

Rino Raj
Rino Raj

Reputation: 6264

Please try this

$( documnet ).delegate( ".prod", "change", function() {
  var dataid = $(this).data('id');
  alert (dataid);
});

Since you are adding the element dynamically you should use delegate(). It attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements

Upvotes: 1

Related Questions