Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jquery document.on() on elements that are pulled in via Ajax?

I have a Jquery Mobile shell page, which I'm loading a form into using Ajax. The form has some checkboxes, which I need to bind to.

Oddly, I can get it to work setting the listener directly on the button like so:

$('input[name="ohneiln"]').on('change', function() {
   alert("hello");
   });

But when I'm trying to set the listener to $(document) and delegate to the checkbox, the listener never fires:

$(document).on('change', 'input[name="ohneiln"]', function() {
   alert("hello");
});

Question:
What is the correct way to set an event binding for "dynamic" elements being loaded in via Ajax using $(document).on()? Is this not possible for change events or why am I running into troubles?

Thanks for help!

like image 707
frequent Avatar asked Jun 02 '12 18:06

frequent


1 Answers

The way the .on() method works changes according to how you use it. In your first example the .on() method behaves similar to bind and will only work on elements that already exist.

The second example behaves like .live() or delegate() in many ways. And will work for elements that are added later.

Read the docs for a detailed explanation http://api.jquery.com/on/

like image 73
codaniel Avatar answered Oct 23 '22 07:10

codaniel