I have a web form that is built dynamically with dozens/hundreds of form element text fields.
Is there a way to use $().change(function(){});
or some other method to (a) evoke jQuery/Ajax to do something in the background and to (b) capture which specific form element actually changes and use its changed value?
I can handle the Ajax portion. I have been unsuccessful with the onChange event.
Thanks.
* JS FILE LOOKS LIKE THIS *
jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions
$(document).ready(function(){
$('a[rel^="prettyPhoto"]').prettyPhoto({
changepicturecallback: function() {
//alert('have focus');
}
});
//find all the form elements in your form,
//then bind an event handler to all of the elements for the `change` event
$('#my-form').find('input, textarea').on('change', function (event) {
//this now refers to the "changed" element
var name = this.name,
value = this.value,
id = this.id,
dObj = {};//create object to pass as data parameter to AJAX request
//set the key as the name of the input, and the value as the value of the input
dObj[name] = value;
$.ajax({
url : '<url>',
data : dObj,//pass the data object
//success : function (data) { ... },
success : alert('changed CCC'),
error : function (jqXHR, textStatus, errorThrown) { /*don't for get to deal with errors*/ }
});
});
$('#my-form').on('change', 'input, textarea', function (event) {
alert('changed AAA');
});
$(document).on('change', '#my-form input, #my-form textarea', function (event) {
alert('changed BBB');
});
}); // end .ready()
// window.parent.closePP();
//find all the form elements in your form,
//then bind an event handler to all of the elements for the `change` event
$('#my-form').find('input, textarea').on('change', function (event) {
//this now refers to the "changed" element
var name = this.name,
value = this.value,
id = this.id,
dObj = {};//create object to pass as data parameter to AJAX request
//set the key as the name of the input, and the value as the value of the input
dObj[name] = value;
$.ajax({
url : '<url>',
data : dObj,//pass the data object
success : function (data) { ... },
error : function (jqXHR, textStatus, errorThrown) { /*don't for get to deal with errors*/ }
});
});
If you are adding the elements after the page-load, then you can use event delegation to bind to the elements that will be in the DOM:
$('#my-form').on('change', 'input, textarea', function (event) {
...
});
This assumes that the #my-form
is in the DOM at the time of binding, otherwise you could bind to the document
:
$(document).on('change', '#my-form input, #my-form textarea', function (event) {
...
});
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