我想限制在第二个列表框中多次添加同一个项目,我想我非常接近它。请帮忙
<script type="text/javascript">
function CopyFile() {
var firstListBox = document.getElementById('<%= lstFirstBox.ClientID %>');
var secondListBox = document.getElementById('<%= lstTarget.ClientID %>');
for (var i = 0; i < firstListBox.options.length; i++) {
if (firstListBox.options[i].selected) {
for (var j = 0; j < secondListBox.options.length; j++) {
if (firstListBox.options[i].selected == secondListBox.options[j]) {
alert("Multiple selection will not allow");
}
else {
var newOption = document.createElement("option");
newOption.text = firstListBox.options[i].text;
newOption.value = firstListBox.options[i].value;
secondListBox.options[secondListBox.options.length] = newOption;
firstListBox.options[i].selected = false;
}
}
}
}
return false;
}
</script>
答案 0 :(得分:1)
我给你写了一个例子。以下html页面有两个选择和一个按钮。如果您在第一个选择中选择一个选项并按下该按钮,该选项将被复制到第二个选择,除非它已经存在。在最后一种情况下,它会提醒一条消息。尝试一下,将其粘贴到文件中(例如“test.htm”)并在浏览器中打开。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function tryToCopy() {
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
var optionToBeCopied = select1.options[select1.selectedIndex];
var contains = false;
for(var i = 0, ceiling = select2.options.length; i < ceiling; i++) {
if(select2.options[i].value == optionToBeCopied.value) {
contains = true;
break;
}
}
if(contains) {
alert("duplicate options are not allowed.");
} else {
var option = document.createElement("option");
select2.appendChild(option);
option.value = optionToBeCopied.value;
option.text = optionToBeCopied.text;
}
}
</script>
</head>
<body>
<select id="select1">
<option value="" selected="true"></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="select2">
</select>
<input type="button" value="tryToCopy" onclick="tryToCopy()"/>
</body>
</html>