使用JavaScript动态生成选择选项下拉菜单

时间:2014-05-22 09:49:37

标签: javascript html drop-down-menu html-select

这是我要创建的选择菜单。但是你可以看到有静态数据。因为我实际上有从后端servlet传递的大量JSON数据,因此将有数百个项目用于选项。我想要为我的下拉框动态生成选项菜单。

<select id="brand-select" name="brand">
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
    <option value="lexus">Lexus</option>
</select>

这是我的试用版,它不起作用:

HTML:

<select id="brand-select" name="brand" onChange="createOptions">
    <option value="none"></option>
</select>

JavaScript的:

//Asssume I have jsonDataForBrands ready, and it contains 100s items
function createOptions() {
    for (var fieldIndex in jsonDataForBrands) {
        html += '<option value=' + fieldIndex  + '>' + jsonDataForBrands[field].title + '</option>';
}

3 个答案:

答案 0 :(得分:2)

我自己想出来了......

HTML:

<select id="brand-select" name="brand">
                </select>

JavaScript的:

function creatBrandOptions(){
    for (var field in jsonDataForBrands) {
         $('<option value="'+ jsonDataForBrands[field].name +'">' + jsonDataForBrands[field].title + '</option>').appendTo('#brand-select');
    }
}

我做了一个Ajax调用,从我的servlet中检索JSON数据,然后在同一个函数BTW中检测creatBrandOptions()...

答案 1 :(得分:1)

你打败了我。这是使用jquery向select添加选项的完整简化示例:

<html>
<head>
<script src="jquery.js"></script>

</head>
<body>
<button id="populateMenu" >Populate menu</button>

<select id="mySelect">


</select>

<script>
    var optionValues= [[1,"first"],[2,"second"]];

    jQuery("#populateMenu").click( function () {
        for (var i=0;i<optionValues.length;i++){
            jQuery('#mySelect').append(jQuery("<option></option>").val(optionValues[i][0]).text(optionValues[i][1]))
        }
    });
</script>
</body>
</html>

答案 2 :(得分:0)

此示例使用jQuery。看看它是否适合你:

function createOptions( jsonDataForBrands ) {
   $('#brand-select option').remove(); // first remove all options
   for (var i=0; i<jsonDataForBrands.length; i++)

   for (var fieldIndex in jsonDataForBrands) { // then populatem them
      $('#brand-select').append($("<option></option>").attr("value", fieldIndex  ).text(jsonDataForBrands[field].title) );
}
相关问题