I’m using Ruby on Rails to populate a database from a form that has multiple input text or select fields. I’m using AJAX so that every time the user makes a change in any input field, all input fields values are automatically taken into account and some other result fields get refreshed.
Everything works fine with the following script for the 1st 2 input fields, but I’m planning to have 50+ input fields if not more, and I wonder if there is a smarter way to implement my script without explicitly defining a separate function for each field.
I’d appreciate any idea how to scale my script without repeating the same thing 50+ times?
This is my js
<script type="text/JavaScript">
$(function(){
$('.input_1_class').bind('change', function(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input_1: $('.input_1_class').val(),
input_2: $('.input_2_class').val(),
}
});
});
$('.input_2_class').bind('change', function(){
$.ajax({
url: "<%= update_fields_projects_url %>",
data: {
input_1: $('.input_1_class').val(),
input_2: $('.input_2_class').val(),
}
});
});
});
</script>
and this is my Ruby form (simplified)
<%= form_for(@project, :html => {:name => "ProjectInfo"}) do |f|
field_set_tag "Customer Information" do %>
<div class="field">
<%= f.label :"Input 1" %>
<%= f.text_field :Input_1, {:class=>"input_1_class"} %>
<%= f.label :"Input 2" %>
<%= f.text_field :Input_2, {:class=>"input_2_class"} %>
<%= f.label :"Output 1" %>
<%= f.text_field :Output_1, {:id=>"output_1_id"} %>
</div>
<% end %>
<% end %>
You can specify multiple selectors, and have the same event bound to all of them: