Change second select list based on first select list value in rails
First you fire an ajax
call to your controller
. (Keep in mind that this url
from the ajax
call 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
})
});
Next you make your action
inside 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
With this, on your success
callback of your ajax
call, you get a JSON
object with your list. So you need to clear the staff
select and create the options and append 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 didn't put the code that create the options and put them inside the list, but a simple search will have plenty of results about this. The idea is simple though.
Populate dropdown list upon selecting a value from another dropdown list
change your city_stats method like. This method should return id and name
def city_stats
@state = params[:state]
@cities = City.where(:state => state).select(:id, :name)
respond_to do |format|
format.json { render :json => @cities }
end
end
Change your each function in ajax call like this.Since data in response is array of object we are using value.id, value.name .
$.each(data,function(key, value) {
listitems += '<option value="' + value.id + '">' + value.name + '</option>';
});
Use jQuery to change a second select list based on the first select list option
$("#select1").change(function() { if ($(this).data('options') === undefined) { /*Taking an array of all options-2 and kind of embedding it on the select1*/ $(this).data('options', $('#select2 option').clone()); } var id = $(this).val(); var options = $(this).data('options').filter('[value=' + id + ']'); $('#select2').html(options);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><select name="select1" id="select1"> <option value="1">Fruit</option> <option value="2">Animal</option> <option value="3">Bird</option> <option value="4">Car</option></select>
<select name="select2" id="select2"> <option value="1">Banana</option> <option value="1">Apple</option> <option value="1">Orange</option> <option value="2">Wolf</option> <option value="2">Fox</option> <option value="2">Bear</option> <option value="3">Eagle</option> <option value="3">Hawk</option> <option value="4">BWM<option></select>
Rails 4 - dynamically populate 2nd select menu based on choice in first select menu in a nested form
In provided example seems that you selecting wrong DOM elements. Just reference them by id, it will be more clear and it will be not so coupled with attributes naming.
I suggesting the next approach for your task.
First build the map of selects on client side:
var optionsMap = {
'Risk of harm': [
'Physical Harm',
'Psychological distress or discomfort',
'Social disadvantage',
'Harm to participants',
'Financial status',
'Privacy'
],
'Informed consent': [
'Explanation of research',
"Explanation of participant's role in research"
],
'Anonymity and Confidentiality': [
'Remove identifiers', 'Use proxies', 'Disclosure for limited purposes'
],
'Deceptive practices': [
'Feasibility'
],
'Right to withdraw': [
'Right to withdraw from participation in the project'
]
};
Then just listen for changes of main select and rebuild options for sub select.
jQuery('#main_category').change(function() {
var category = jQuery(this).val(),
$subCategory = jQuery('#sub_category'),
newOptions = optionsMap[category];
$subCategory.empty();
$.each(newOptions, function(key,value) {
$subCategory.append(jQuery("<option></option>").attr("value", value).text(key));
});
})
Here an example how it looks like with plain html form
jQuery(document).ready(function() { var optionsMap = { 'Risk of harm': [ 'Physical Harm', 'Psychological distress or discomfort', 'Social disadvantage', 'Harm to participants', 'Financial status', 'Privacy' ], 'Informed consent': [ 'Explanation of research', "Explanation of participant's role in research" ], 'Anonymity and Confidentiality': [ 'Remove identifiers', 'Use proxies', 'Disclosure for limited purposes' ], 'Deceptive practices': [ 'Feasibility' ], 'Right to withdraw': [ 'Right to withdraw from participation in the project' ] };
jQuery('#main_category').change(function() { var category = jQuery(this).val(), $subCategory = jQuery('#sub_category'), newOptions = optionsMap[category]; $subCategory.attr('disabled', false) $subCategory.empty(); $.each(newOptions, function() { $subCategory.append(jQuery("<option></option>").text(this)); }); })});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form> <select id='main_category'> <option disabled selected value> -- select an option -- </option> <option>Risk of harm</option> <option>Informed consent</option> <option>Anonymity and Confidentiality</option> <option>Deceptive practices</option> <option>Right to withdraw</option> </select> <select id='sub_category' disabled> </select></form>
Generating dropdown values based on value of another dropdown in rails
there are two ways for your requirement. One is client side you can change the dropdown value or you can send one server side request and render your required options.
For client side you can do like this:
<div class="col">
<div class="form-group">
<%= form.select :bug_type, options_for_select([["Bug", "bug"], ["Feature", "feature"]]) %>
</div>
</div>
<div class="col">
<div class="form-group">
<% if @bug.bug_type == "bug" %>
<%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Completed", "completed"]]) %>
<% else %>
<%= form.select :status, options_for_select([["Initial", "initial"], ["Started", "started"], ["Resolved", "resolved"]]) %>
<% end %>
</div>
</div>
<script>
// Please change selector accoding to your DOM.
// This is bug type select dropdown
$('#bug_type_select').change(function() {
var selectedValue = $('#bug_type option:selected').val();
var bugOptions = {
'initial': 'Initial',
'started': 'Started',
'completed': 'Completed'
}
var featureOptions = {
'initial': 'Initial',
'started': 'Started',
'resolved': 'Resolved'
}
// Please change selector accoding to your DOM.
// This is status select dropdown
var $mySelect = $('#mySelect');
$mySelect.empty();
if (selectedValue === 'bug') {
$.each(bugOptions, function(key, value) {
var $option = $('<option/>', {
value: key,
text: value
});
$mySelect.append($option);
});
} else {
$.each(featureOptions, function(key, value) {
var $option = $('<option/>', {
value: key,
text: value
});
$mySelect.append($option);
});
}
});
</script>
Related Topics
How to Convert Special Utf-8 Chars to Their Iso-8859-1 Equivalent Using JavaScript
Use Browser Search (Ctrl+F) Through a Button in Website
Ruby on Rails 3.1 - Assets Pipeline - Assets Rendered Twice
Adding Click Event Handler to Iframe
How to Format a Utc Date as a 'Yyyy-Mm-Dd Hh:Mm:Ss' String Using Nodejs
What Is the "Best" Way to Get and Set a Single Cookie Value Using JavaScript
Applying Classname/Onclick/Onchange Not Working on Custom React Component
Backbone.Js Empty Array Attribute
Meteor: Calling an Asynchronous Function Inside a Meteor.Method and Returning the Result
How to Enable Touch on Multiple Buttons Simultaneously in React Native
Is There a Jquery Autogrow Plugin for Text Fields
Why Is the Ecc-Dh Symmetric Key of This Site Different from Openssl
Passing Functions to Settimeout in a Loop: Always the Last Value
Sorting Arrays Numerically by Object Property Value
Using Socket.Io in Express 4 and Express-Generator's /Bin/Www
Create an Object from an Array of Keys and an Array of Values
JavaScript Es6 Array Feature [...Data, 0] "Spread Operator"
How to Update Single Value Inside Specific Array Item in Redux