如何使用Javascript动态设置我的html选择字段中的选项? 这是我的页面设置:使用JavaScript动态设置选择选项
<form name="test">
<table>
<tr>
<td class='dataleft'>Product: </td>
<td><select name='inptProduct'></select></td>
</tr>
</table>
</form>
我有一个数组中的所有值。这是设置<option>
的位置。
for(var i = 0; i < productArray.length; i++) {
console.log("<option value='" + productArray[i] + "'>" + productArray[i] + "</option>");
}
PS:可以使用jQuery。
解决方案: 这是我一直在寻找最终的解决方案。它不会将新选项应用于选择字段。它消除了所有的第一,然后添加新的:
var optionsAsString = "";
for(var i = 0; i < productArray.length; i++) {
optionsAsString += "<option value='" + productArray[i] + "'>" + productArray[i] + "</option>";
}
$("select[name='inptProduct']").find('option').remove().end().append($(optionsAsString));
http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery – 2012-04-20 13:41:15
http:///stackoverflow.com/questions/47824/how-do-you-remove-all-the-options-of-a-select-box-and-then-add-one-option-andsese – AbiusX 2015-02-20 01:27:13