I'm adding select elements dynamically, like in the below HTML. I'm not sure why the .on('change' ...) is not working for the dynamic select. What am I missing?
I'm using Chrome 24.0.1312.57 + jquery 1.8.3.
<script type="text/javascript"> $(document).ready(function() { $('#x select').on('change', function () { alert('helo'); }) $('#y select').on('change', function () { alert('helo'); }) $('#x').html($('#y').html()); }); </script> <div id="x"></div> <div id="y"> <select> <option>O1</option> <option>O2</option> </select> </div>
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). The jQuery set receives the event then delegates it to elements matching the selector given as argument.
$(document). ready(function() { $('body'). on('click', '. AddEl', function() { var $elems = $('.
Definition and Usage The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.
In this example, we should go with the following steps to implement dynamic data loading using jQuery. Create UI to be appended for each user information. Download and import latest version of jQuery library files and jQuery UI files. Create custom jQuery handlers to append UI and load dynamic data into it.
Your code:
$('#x select').on('change', function () { alert('helo'); })
attaches an event handler to the select inside the #x element.
What you want (from what i understood) is something in the lines of:
$("#y").on('change','select',function () { alert('helo'); });
This attaches an event handler to the #y element that gets delegated to its children 'select' elements
From http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
Event binding to elements that are not in the DOM on initial page load will not work. You need to bind to an element further up the DOM that exists to allow the event to trickle down. This is usually the approach that I take:
$(document).on({ change: function() { alert('helo'); } }, '#x select'); $(document).on({ change: function() { alert('helo'); } }, '#y select');
I prefer it as you can add subsequent events easily.
$(document).on({ change: function() { alert('helo'); }, blur: function() { alert('helo'); } }, '#x select');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With