使用 JavaScript 动态设置选择选项 [英] Dynamically set select-options with JavaScript

查看:27
本文介绍了使用 JavaScript 动态设置选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I dynamically set the options from my html select field with Javascript? This is my page setup:

<form name="test">
  <table>
    <tr>
      <td class='dataleft'>Product: </td>
      <td><select name='inptProduct'></select></td>
    </tr>
  </table>
</form>

我有一个数组中的所有值.这是设置 s 的位置.

I have all values in an array. This is the location to set the <option>s.

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

PS:可以使用jQuery.

PS: jQuery can be used.

解决方案:这是我正在寻找的最终解决方案.它不会将新选项应用于选择字段.它首先删除所有,然后添加新的:

Solution: This is the final solution I was looking for. It does not apply the new options to the select field. It removes all first, and then adds the new ones:

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));

推荐答案

你几乎已经做到了:

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

EDIT 移除了最后一个 optionsAsString 的 $ 包装器,因为 append 会自动转换字符串

EDIT removed $ wrapper around last optionsAsString as append automatically converts strings

这篇关于使用 JavaScript 动态设置选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆