Change the second picklist based on the first picklist value in rails
Updated with response code below
For the second selection box, select the options to select only those staff members
associated with the selection team
.
the form:
Example example . The user selects a different team. The employee selects update options to only display those employees who are associated with that selected team.
I know the solution is javascript related, but I am having trouble applying it in a rails environment. I know this question , but I still have problems applying it in my rails application.
code
#app/controllers/task_notes_controller.rb
...
def new
@task_note = TaskNote.new
@teams = Team.all.includes(:staff_members)
end
...
#app/views/task_notes/_form.html.erb
...
<%= select_tag('team', options_from_collection_for_select(@teams, :id, :name ) ) %>
<div class="field">
<%= f.label :staff_member_id %><br>
# Currently displays all staff members on every team, no matter what team is selected.
<%= f.collection_select :staff_member_id, StaffMember.all, :id, :first_name %>
</div>
...
#app/assets/javascripts/task_notes.js
$(document).ready(function(){
$("#team").on('change', function(){
alert("The new team id is: " + $(this).val() );
# The value (the id of the team) does update on selection option change.
# Now I need to specify that I want the select options for the staff members
# select box to update and show only staff members with this team_id
});
});
source to share
First, you start a call ajax
to yours controller
. (Keep in mind that this one url
of the call ajax
must exist in your routes).
$(document).ready(function() {
$("#team").on('change', function(){
$ajax({
url: "populate_other_list",
type: "GET",
data: {team_id: $(this).val()},
// Callbacks that will be explained
})
});
Then you will contribute action
to your controller
.
def populate_other_list
team_id = params[:team_id]
@staff = Staff.find_by team_id: team_id
respond_to do |format|
format.json { render json: @staff }
end
end
That said, when success
you callback your call, ajax
you get an object JSON
with your list. So you need to clear staff
, select and create options and add to it.
// Ajax call
success: function(data) {
$("#staff_member_id").children().remove();
// Create options and append to the list
}
// Rest of Ajax call
As you can see, I did not put the code that created the parameters and put them in the list, but a simple search will have many results on this. The idea is simple though.
source to share