I have a script that handles input changes and triggers ajax requests accordingly.
$(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 script works perfectly for handling input changes and executing ajax updates. Now, I want to trigger the same ajax request when a specific button is clicked.
<input type=button id=update_button_id value="Update Fields" class=update_button_class>
Instead of duplicating the previous function with slight modifications, I'm looking for a better solution where I can write the function once and trigger it from either an input change or a button click event.
Update1:
Here's a more efficient way to handle 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:
Another attempt to simplify the function:
$('.input1_class, .input2_class, ...').bind('change',updateFields);
However, this approach did not work as expected.
Update3:
Finally, I found a solution that worked for me by binding the function to the change event on input elements:
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();">