user1260827
user1260827

Reputation: 1520

bind to event for element created dynamically. (jQuery 1.7.2)

I have a js file. It contain the following code:

$("#speedB").change(function () {

    var date = $(this).val();
    $('.fl_near a').removeClass('selected');
    var clientId = $('#wiz_main').data('client');
    var eventId = $('#wiz_main').data('event');
    $.get('/desk/GetSessionScreen', { clientId: clientId, eventId: eventId, date: date }, function (data) {
        $('#step1').html(data);
    });
});

The problem in that element with id speedB not exist on page when page is loaded. It appears later after ajax request. How can I bind event for element created later using jQuery 1.7.2 (methodon`)? Thanks.

Upvotes: 1

Views: 4009

Answers (4)

Federico
Federico

Reputation: 6468

Try binding the function within the scope of the function where you dynamically create the element.

Upvotes: 0

JoeFletch
JoeFletch

Reputation: 3960

You need to use $.on(). Something like this.

$("body").on("change", "#speedB", function() { . . . your code here . . . })

The first selector, $("body"), should be an element that will always be on the page so that when the event bubbles up to it, the action that you desire will take effect.

"#speedB" needs to be the second argument of .on(), the element that will trigger the event.

Check out the jQuery page for more details. $.on()

Upvotes: 3

Musa
Musa

Reputation: 97672

Use .on()

$(document).on("change", "#speedB").(function () {

Upvotes: 5

Ram
Ram

Reputation: 144659

Try this:

$(document).on('change', '#speedB', function(){
  // ...
})

Upvotes: 1

Related Questions