如何使用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