[英]Storing the option values of a select box and storing them into a variable (by comma separated values)
[英]Adding option values to a select box by comma spaced values
如何修改下面的代码,以便可以将单个和逗号分隔的值添加到选择框?
示例1:橙色
[选择框]
orange
范例2:红色,蓝色,绿色,黄色
[选择框]
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>
只需用逗号分隔值,然后遍历每个字符串,然后随便添加选项:
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])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.