繁体   English   中英

使用JavaScript动态设置选择选项

[英]Dynamically set select-options with JavaScript

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

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

wellyou几乎完成了所有这些:

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 $ wrapper,因为append自动转换字符串

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

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

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

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

例:

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>
function onLoad() {

  var type = new Array("Saab","Volvo","BMW");

    var $select = $("select[name='XXXXXType']")
    alert($select);
    $(type).each(function(i, v){
        $select.append($("<option>", { value: v, html: v }));
      });

}
<select name="XXXXXType" id="XXXXXType"></select>

如果你不坚持使用纯JavaScript来完成这项工作,你可以使用jQuery轻松完成这项工作。

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


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

请注意,这里我使用了select标签的id。 这也是我添加html部分的原因。 希望你知道如何添加jQuery。

我通常这样做:

document.getElementById("selectid").innerHTML="<option value='foo'>FOO</option>" ;

你可以为select id = inptProduct设置id然后执行$('#inptProduct')。val(yourselectValue)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM