[英]jQuery populate 2nd select menu based on value select in 1st select menu
[英]Rails 4 - dynamically populate 2nd select menu based on choice in first select menu in a nested form
我的Rails 4應用程序中有Project和Ethic模型。
道德視圖包含一個嵌套的字段表單(使用簡單的表單簡單字段)。 道德表單字段嵌套在項目表單中。
道德形式字段有2個選擇菜單。 第一個菜單為一個類別提供了一組選項。 第二個選擇選項是子類別列表。
我正在嘗試根據第一個選擇菜單中的選擇,弄清楚如何使用正確的選項填充第二個選擇菜單。
在我的project.js文件中,我有:
jQuery(document).ready(function() {
jQuery("#project_ethic_attributes.main_category").change(function() {
var category = $("#project_ethic_attributes.main_category").val(),
sub_category = $("#project_ethic_attributes.sub_category"),
options = [],
str = "";
sub_category.find('option').remove();
if(category == 'Risk of harm'){
options = ["Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]
}
});
// jQuery(".main_category").change(function() {
// var category = $(".main_category").val(),
// sub_category = $(".sub_category"),
// options = [],
// str = "";
// sub_category.find('option').remove();
// if(category == 'Risk of harm'){
// options = ["Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]
// }
// else if(category == 'Informed consent'){
// options = ["Explanation of research", "Explanation of participant's role in research"]
// }
// else if(category == 'Anonymity and Confidentiality'){
// options = ["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]
// }
// else if(category == 'Deceptive practices'){
// options = ["Feasibility"]
// }
// else if(category == 'Right to withdraw'){
// options = ["Right to withdraw from participation in the project"]
// }
// if(options.length > 0){
// for(i=0;i<options.length;i++){
// str = '<option value="' + options[i] + '">' + options[i] + '</option>'
// sub_category.append(str);
// }
// sub_category.val(options[0]);
// }
});
我無法弄清楚我做錯了什么。 無論我在第一個選項中做出何種選擇,第二個選擇菜單都會填充屬於最后一個類別的選項。
我的項目形式有:
<%= f.simple_fields_for :ethics do |f| %>
<%= render 'ethics/ethic_fields', f: f %>
<% end %>
<%= link_to_add_association 'Add an ethics consideration', f, :ethics, partial: 'ethics/ethic_fields' %>
我的道德形式領域有:
<%= f.input :category, collection: [ "Risk of harm", "Informed consent", "Anonymity and Confidentiality", "Deceptive practices", "Right to withdraw"], :label => "Principle", prompt: 'select', id: "main_category" %>
<%= f.input :subcategory, collection: text_for_subcategory(@category), :label => "Subcategory", prompt: 'select', id: "sub_category" %>
我的道德觀助手有:
def text_for_subcategory(category)
if category == 'Risk of harm'
[ "Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]
elsif category == 'Informed consent'
["Explanation of research", "Explanation of participant's role in research"]
elsif category == 'Anonymity and Confidentiality'
["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]
elsif category == 'Deceptive practices'
["Feasibility"]
else category == 'Right to withdraw'
["Right to withdraw from participation in the project"]
end
end
任何人都可以看到我需要做什么來根據第一個選擇菜單中的選擇使用正確的選項填充第二個選擇菜單。 我想知道我是不是應該在project.js文件中編寫jQuery,因為表單字段包含在ethic視圖partial(在項目表單中呈現)中。
MIXAN的建議
我的表格現在有:
<%= f.input :category, collection: [ "Risk of harm", "Informed consent", "Anonymity and Confidentiality", "Deceptive practices", "Right to withdraw"], option:'disabled selected value', :label => "Principle", prompt: 'select', id: "main_category" %>
<%= f.input :subcategory, :label => "Subcategory", prompt: 'select', id: "sub_category", option:'disabled' %>
我不得不稍微更改表單,因為我使用帶有rails的簡單表單。 我不確定是否已將“禁用選定值”和“禁用”選項正確添加到表單輸入中。
目前,表單呈現 - 但第二個菜單沒有填充任何內容。 我想知道這是否與在js文件中使用選項標簽有關?
ethics.js有:
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));
});
})
});
MIXAN的修改建議
<%= f.select :category, collection: [ "Risk of harm", "Informed consent", "Anonymity and Confidentiality", "Deceptive practices", "Right to withdraw"], option:'disabled selected value', :label => "Principle", prompt: 'select', html: { id: "main_category" } %>
<%= f.select :subcategory, [], {}, id: "sub_category", disabled: true %>
當我嘗試這個時,第一個類別的菜單下拉列表的格式被更改,但功能與我使用f.input時的功能相同。 第二個菜單不會填充任何選項。
使用此代碼,為#id
和urls
編輯它
// Dynamic Search Model Loader
$(function(){
var saved = {};
var options, value;
$("#selectOne").change(function(){
options = '<option value="" selected="selected">Loading...</option>';
$("#selectTwo").html(options);
value = $(this).val();
if (saved[value].length > 0) {
$("#selectTwo").html(saved[value]);
} else {
$.ajax({
url: '/api/get-json-values/?category=' + value, // Set the category as the value or whatever you want it to be
type: 'GET',
dataType: 'json',
async: true
}).done(function(data){
options = '<option value="" selected="selected">Please Pick...</option>';
// Parse through the values
$.each(data, function(text){
options += '<option value="' + text + '">' + text + '</option>';
});
// Populate the second select menu
$("#selectTwo").html(options);
saved[value] = options;
}).fail(function(data){
options = '<option value="" selected="selected">Empty...</option>';
$("#selectTwo").html(options);
}); // End Ajax
};
}); // End Change
});
根據需要對其他選擇菜單重復此操作
需要您在控制器中創建一個操作,該操作返回包含所需值的JSON。
** Routes.rb **
namespace :api do
get 'get-json-values', to: 'queries#category_search'
end
控制器代碼:
class API::Queries < ApplicationController
def category_search
category = params[:category]
if category == 'Risk of harm'
@json = [ "Physical Harm", "Psychological distress or discomfort", "Social disadvantage", "Harm to participants", "Financial status", "Privacy"]
elsif category == 'Informed consent'
@json = ["Explanation of research", "Explanation of participant's role in research"]
elsif category == 'Anonymity and Confidentiality'
@json = ["Remove identifiers", "Use proxies", "Disclosure for limited purposes"]
elsif category == 'Deceptive practices'
@json = ["Feasibility"]
elsif category == 'Right to withdraw'
@json = ["Right to withdraw from participation in the project"]
else
@json = nil
end
if @json
render json: @json.to_json, status: 200
else
render json: {message: 'Not Found'}, status: 404
end
end
end
然后它將通過它們並將它們作為選項添加到從屬選擇菜單
在提供的示例中,您似乎選擇了錯誤的DOM元素。 只需通過id引用它們,它就會更清晰,並且不會與屬性命名相結合。 我建議你的下一個方法來完成你的任務。 首先在客戶端構建選擇映射:
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.empty();
$.each(newOptions, function(key,value) {
$subCategory.append(jQuery("<option></option>").attr("value", value).text(key));
});
})
這里是一個簡單的html表單的示例
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.