I have the following script
$(function(){
$('.input1_class, .input2_class, <many other input classes go here>').bind('change', function(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input1: $('.input1_class').val(),
input2: $('.input2_class').val(),
<other inputs go here>
}
});
});
});
this is working fine, so if any input is modified, the proper actions are executed and ajax update also runs fine.
Now I wanted to trigger the same ajax request from the click of the following button
<input type=button id=update_button_id value="Update Fields" class=update_button_class>
I was about to duplicate the previous function by changing the header as follows, which I think would work
$(function(){
$('.update_button_class').bind('click', function(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input1: $('.input1_class').val(),
input2: $('.input2_class').val(),
<other inputs go here>
}
});
});
});
but I thought that’s not a good solution, because any subsequent changes would have to done in both functions at the same time.
I wonder if there is a better way to write this function only once and to trigger it either from an input “change” or a button “click”
Update1:
I changed to this
function updateFields(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input1: $('.input1_class').val(),
input2: $('.input2_class').val(),
<other inputs go here>
}
});
}
$('.input1_class, .input2_class, <many other input classes go here>').change(updateFields);
<input type=button id=apply_button_id value="Apply Updates" class=apply_button_class onClick="updateFields();">
Update2 :
I also tried
$('.input1_class, .input2_class, ...').bind('change',updateFields);
and that did not work either
Update3 :
The following is what worked for me
function updateFields(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input1: $('.input1_class').val(),
input2: $('.input2_class').val(),
<other inputs go here>
}
});
}
$(function(){
$('.input1_class, .input2_class, ...').bind('change',updateFields);
});
<input type=button id=apply_button_id value="Apply Updates" class=apply_button_class onClick="updateFields();">
Just give the function a name:
Or even:
And then: