使用JavaScript动态设置选择选项

nim*_*rod 44 javascript jquery

如何使用Javascript从我的html选择字段动态设置选项?这是我的页面设置:

<form name="test">
  <table>
    <tr>
      <td class='dataleft'>Product: </td>
      <td><select name='inptProduct'></select></td>
    </tr>
  </table>
</form>
Run Code Online (Sandbox Code Playgroud)

我在数组中有所有值.这是设置<option>s 的位置.

for(var i = 0; i < productArray.length; i++) {
    console.log("<option value='" + productArray[i] + "'>" + productArray[i] + "</option>");
}
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

got*_*itz 43

wellyou几乎完成了所有这些:

var optionsAsString = "";
for(var i = 0; i < productArray.length; i++) {
    optionsAsString += "<option value='" + productArray[i] + "'>" + productArray[i] + "</option>";
}
$( 'select[name="inptProduct"]' ).append( optionsAsString );
Run Code Online (Sandbox Code Playgroud)

EDIT在最后删除了$ wrapper,optionsAsString因为它append自动转换字符串

  • @vemv*再次* - 也许是时候创建一个这样做的函数了 (3认同)

hun*_*ter 23

var $inputProduct = $("select[name='inputProduct']")

$(productArray).each(function(i, v){ 
    $inputProduct.append($("<option>", { value: v, html: v }));
});
Run Code Online (Sandbox Code Playgroud)

  • 在循环之前写`$ inputProduct.html("")`以清除当前选项 (3认同)

Luk*_*son 7

假设该数组productArray是一个简单数组,每个元素都是选项的值以及该选项所需的标题。

$( 'select[name="inptProduct"]' )
  .html( '<option>' + productArray.join( '</option><option>' ) + '</option>' );
Run Code Online (Sandbox Code Playgroud)

例子:

productArray = ['One', 'Two', 'Three'];

// With the original code being

<select name="inptProduct">
  <option>There could be no options here</option>
  <option>Otherwise, any options here will be overwritten</option>
</select>

// Running the code above would output

<select name="inptProduct">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>
Run Code Online (Sandbox Code Playgroud)