Javascript 更改选择列表的选项数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6364748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:25:49  来源:igfitidea点击:

Change the options array of a select list

javascripthtmlmootools

提问by Shakur

Is there a way to change the options array of an html select list using javascript or mootools?

有没有办法使用javascript或mootools更改html选择列表的选项数组?

I need to replace the entire options set with a new one. In my ajax response I receive an array filled in with with the new HTML options, so I try to empty the old list and add new values as follows

我需要用一个新选项替换整个选项集。在我的 ajax 响应中,我收到一个填充有新 HTML 选项的数组,因此我尝试清空旧列表并添加新值,如下所示

$('element').options.length=0;
for (i=0; i<newSet.length; i++)
{
    $('element').options[i]=newSet[i];
}

The above code gives me an uncaught exception on the line inside the loop.

上面的代码在循环内的行上给了我一个未捕获的异常。

uncaught exception: [Exception... "Unexpected error" nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame

未捕获的异常:[异常......“意外错误”nsresult:“0x8000ffff(NS_ERROR_UNEXPECTED)”位置:“JS框架

Just to add what worked for me:

只是添加对我有用的内容:

/* get new options from json*/
var new_options = response.options;

/* Remove all options from the select list */
$('idresource').empty();
/* Insert the new ones from the array above */
for (var key in new_options)
{
var opt = document.createElement('option');
    opt.text = new_options[key];
    opt.value = key;
    $('idresource').add(opt, null);
}

采纳答案by Bj?rn

var new_options = ['Option 1', 'Option 2', 'Option 3'];

/* Remove all options from the select list */
$('yourSelectList').empty();

/* Insert the new ones from the array above */
$each(new_options, function(value) {
    new Element('option')
        .set('text', value)
        .inject($('yourSelectList'));
});

回答by amit_g

HTML

HTML

<select class="element">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<button><<<</button>

<select class="newSel">
    <option value="11">NewOne</option>
    <option value="22">NewTwo</option>
    <option value="33">NewThree</option>
</select>

Javascript

Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

$("button").click(function(){
    var oldSel = $('.element').get(0);

    while (oldSel.options.length > 0) {
        oldSel.remove(oldSel.options.length - 1);
    }

    var newSel = $('.newSel').get(0);

    for (i = 0; i < newSel.length; i++)
    {
        var opt = document.createElement('option');

        opt.text = newSel.options[i].text;
        opt.value = newSel.options[i].value;

        oldSel.add(opt, null);
    }
})

Demo

演示

回答by cdkisa

var newOptionsHtml = "<option value='2'>New Option 1</option><option value='3'>New Option 2</option>";

$("#test").html(newOptionsHtml);

回答by Nicolas Giszpenc

Vanilla JS solution

香草JS解决方案

var arrOptions = [];
arrOptions.push("<option value='' selected>Select from List...</option>");
arrOptions.push("<option value='Trust Deposit'>Trust Deposit</option>");
arrOptions.push("<option value='Operating Deposit'>Operating Deposit</option>");

document.getElementById("selectInput").innerHTML = arrOptions.join();

If you already have a set of options

如果您已经有一组选项

var arrOptions = [];
var arrOptionsCollection = document.getElementById("check_typeInput").options;
for (var i=0, n = arrOptionsCollection.length; i < n; i++) { // looping over the options
    if (arrOptionsCollection[i].value) {
        arrOptions.push("<option value='" + arrOptionsCollection[i].value + "'>" + arrOptionsCollection[i].text + "</option>");
    }
}
arrOptions.push("<option value='Trust Deposit'>Trust Deposit</option>");
arrOptions.push("<option value='Operating Deposit'>Operating Deposit</option>");

document.getElementById("selectInput").innerHTML = arrOptions.join();

回答by Prusse

Manipulate the DOM using removeand addon the select object. You can see http://www.w3schools.com/jsref/dom_obj_select.aspfor more info.

使用removeadd在选择对象上操作 DOM 。您可以查看http://www.w3schools.com/jsref/dom_obj_select.asp了解更多信息。

For add new options to some select element I have write the following code:

为了向某些选择元素添加新选项,我编写了以下代码:

/**
    Adds an option to a select(HTML) element.
    @param {HTMLElement} select_element The select eletement.
    @param {string} option_str The text of the option.
    @param {Object} [option_attr] The options to be copied into the option element created.
    @returns {HTMLElement} The option element created.
*/
function addOptionStrToSelectElement(select_element, option_str, option_attr){
    if (!option_attr) option_attr = {};
    var doc = select_element.ownerDocument;
    var opt = doc.createElement("option");
    opt.text = option_str;
    for (var prop in option_attr){
        if (option_attr.hasOwnProperty(prop)){
            opt[prop] = option_attr[prop];
        }
    }
    doc = null;
    if (select_element.add.length === 2){
        select_element.add(opt, null); // standards compliant
    } else{
        select_element.add(opt); // IE only
    }
    return opt;
}