以下函数将动态地将新选项值添加到选择框中。功能强大,但在选择框中添加新选项之前,它不会考虑并检查重复的条目。如何修改代码,以便它会提醒用户已找到重复的条目并中止添加相同的选项值:
function addref() {
var value = document.getElementById('refdocs').value
if (value != "") {
var select = document.getElementById('refdocs_list');
var option = document.createElement('option');
option.text = value
select.add(option,select.option)
select.selectedIndex = select.options.length - 1;
}//end of if
}//end of function
答案 0 :(得分:1)
DEMO: http://jsfiddle.net/abc123/rcwgk/2/
这将有效,这会增加您可能希望以不同方式执行某些操作的值和选项。
<html>
<head>
<script type="text/javascript">
var values = new Array();
var options = new Array();
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
function getOptions() {
var selectobject=document.getElementById("refdocs_list");
for (var i=0; i<selectobject.length; i++){
values.push(selectobject.options[i].value);
options.push(selectobject.options[i].text);
}
}
function addref() {
var value = document.getElementById('refdocs').value
if (value != "" && values.indexOf(value) == -1 && options.indexOf(value) == -1 ) {
values.push(value);
options.push(value);
var select = document.getElementById('refdocs_list');
var option = document.createElement('option');
option.text = value
select.add(option,select.option)
select.selectedIndex = select.options.length - 1;
}//end of if
}//end of function
</script>
</head>
<body onload="getOptions()">
<select id="refdocs_list">
<option value="1">test</option>
</select>
<input type="text" id="refdocs"/>
<input type="button" value="add" onclick="javascript:addref()" />
</body>
</html>