[英]How to retrieve the value of the selected option from a dynamically created select in a table
[英]Load a selected option on a dynamically created `<select>`?
我有一个网页,其中保存了一堆选项(来自<select>
)。 我可以很好地通过PHP和MySQL存储值,然后恢复这些选择的值。
问题来自动态创建的选择。 通过登录到控制台,我可以确认<select>
的HTML已正确加载,并且它们在屏幕上正常运行。 但是它们都不加载存储的值。
我试过使用:
$("#selectID").val(storedVariable);
$("#selectID").prop("selectedIndex", storedIndex);
$("#selectID option[value=" + storedVariable + "]").prop("selected", true);
这些选项均无效。 更糟糕的是,我可以使用控制台检查.val()
或.prop("selectedIndex")
,它们返回正确的值,但是<option>
显示/选择的下拉选项为空白(索引0
)。
同样,这仅适用于动态创建的选择,在工作中进行硬编码的选择就可以了。
这是我正在使用的代码:
file.html
<select id="select1">
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
</select>
<select id="select2"></select>
file.js
// selectedValue1 & selectedValue2 are sent from file.php
console.log(selectedValue1); // -> "choice2"
console.log(selectedValue2); // -> "choice2B"
// these work, I can verify them in the console
$("#select1").val(selectedValue1);
updateSelections();
$("#select2").val(selectedValue2);
function updateSelections() {
$("#select2").html(function() {
var optionChoices = "<option value='blank'> </option>";
if ("#select1".val() == "choice1") {
optionChoices += "<option value='choice1A'>Choice 1A</option>";
optionChoices += "<option value='choice1B'>Choice 1B</option>";
optionChoices += "<option value='choice1C'>Choice 1C</option>";
return optionChoices;
} else if ("#select1".val() == "choice2") {
optionChoices += "<option value='choice2A'>Choice 2A</option>";
optionChoices += "<option value='choice2B'>Choice 2B</option>";
optionChoices += "<option value='choice2C'>Choice 2C</option>";
}
return optionChoices;
}, 0);
}
基本上,selectedValue1可以完美加载,但是selectedValue2不能完美加载。
更新:这是我的应用中应该工作的实际代码行。
console.log(fieldOfStudy);
$("#selectFieldOfStudy").val(fieldOfStudy);
console.log($("#selectFieldOfStudy").val());
console.log()两次都输出正确的存储信息,但是该值未正确显示在屏幕上。
您的代码中有错误。
函数updateSelections
应该在使用之前定义
"#select1".val()
:将"#select1"
包装到$()
还应考虑每次修改第一个select
都更新select2
:
$("#select1").on('change', updateSelections);
参见jsFiddle: https ://jsfiddle.net/xpvt214o/613071/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.