[英]Setting the selected value of a drop down using a javascript variable
I am using JQuery to create dynamic dropdown boxes (the selection of the first drop down filters options in the second). 我正在使用JQuery创建动态下拉框(在第二个选择第一个下拉过滤器选项)。 I am trying to create a check for a reverse use case (selection of second drop down forces associated selection in the first).
我正在尝试为反向用例创建一个检查(选择第二个下拉力与第一个相关的选择)。
I have previously used this code to successfully set the active value: 我之前使用此代码成功设置了活动值:
$("#department option[value='Other']").prop('selected', true);
Now, I am trying to do the same as above, but by using a variable value instead of a hardcoded one. 现在,我试图像上面那样做,但是使用变量值而不是硬编码值。 This is the code I have so far:
这是我到目前为止的代码:
var selected_campus = $("#college")[0].options[$("#college")[0].selectedIndex].text.split(":",1).toString();
$("#campus option[value=selected_campus]").prop('selected', true);
The first line works fine and the desired value is successfully stored in selected_campus
. 第一行工作正常,所需的值成功存储在
selected_campus
。 However, the second line does not. 但是,第二行没有。 How can I set the selected value of
#campus
to selected_campus
? 如何将
#campus
的选定值设置为selected_campus
?
You were close; 你很亲密; you have just to concatenate the variable
selected_campus
with the selector (string) using the +
and single quotes '
sign, like : 你只需要使用
+
和单引号'
符号将变量selected_campus
与选择器(字符串)连接起来,如:
$("#campus option[value='"+selected_campus+"']").prop('selected', true);
________________________^_^_______________^_^
Instead of : 代替 :
$("#campus option[value=selected_campus]").prop('selected', true);
Hope this helps. 希望这可以帮助。
You need to substitute the variable into the code: 您需要将变量替换为代码:
$("#campus option[value='" + selected_campus + "']").prop('selected', true);
You would need the single quotes in case the value has spaces or other characters in it 如果值中包含空格或其他字符,则需要单引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.