In my form, there's a button to add additional elements as needed by the user. For each input field, there's a .change() handler. The issue is that the .change does not fire on appended form elements but still triggers on existing form elements. Any help is appreciated.
$('.element').each(function() {
$mainElement = $(this); // memorize $(this)
$sibling = $mainElement.next('input'); // find a sibling to $this.
$sibling.change(function($mainElement) {
return function() {
$mainElement.text('My textfield changed');
}
}($mainElement));
Jsfiddle demo: http://jsfiddle.net/WCDBr/22
Try the on method:
$(document).on('change', 'input', function() {});
//or
$(document).on('change', '.inputclass', function() {});
It registers the event with the document and it should work even for newly added documents. Your change event registered with existing elements.
Just for the sake of simplicity i copy pasted the code.
On Clicking the "Add" button you not binding the change event again for the newly created element. Do This on Click:
$('#test').click(function(){
$('ul').append('<li><p class="element">Lorem ipsum</p><input/></li>');
$('.element').each(function() {
$mainElement = $(this); // memorize $(this)
$sibling = $mainElement.next('input'); // find a sibling to $this.
$sibling.change(function($mainElement) {
return function() {
$mainElement.text('My textfield changed');
}
}($mainElement));
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.