通过逗号间隔值将选项值添加到选择框

时间:2014-03-24 15:25:10

标签: javascript

如何修改以下代码,以便我能够将单个和逗号分隔的值添加到选择框中?

示例1:橙色

[SELECT BOX]

orange

示例2:红色,蓝色,绿色,黄色

[SELECT BOX]

red
blue
green
yellow

这是HTML

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">
function add() {

var select = document.getElementById('list') 

var option = document.getElementById('reference').value

select.options[select.options.length] = new Option(option, option)

}
</script>

</head>

<body>
<input type="button" value="add" onclick="add()">
<input type="text" id="reference">
<br><br>
<select style="width: 200px;" id="list"><option>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

只需用逗号分隔值,然后遍历每个字符串,随时附加选项:

function add() {
    var select = document.getElementById('list')
    var options = document.getElementById('reference').value.split(',');
    for(i=0; i<options.length; i++){
        select.options[select.options.length] = new Option(options[i], options[i])
    }
}

JSFiddle