防止重复项添加到列表框javascript中 [英] Prevent duplicate items added into listbox javascript
本文介绍了防止重复项添加到列表框javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在以下情况下阻止添加重复项目。
首先,我有一个包含一些选项的列表框,例如
< select id =" listbox"名称= QUOT;列表框"多个= QUOT;多" style =" width:580px;">
< option> Java< / option>
< option> PHP< / option>
< option> Perl< / option>
< option> Javascript< / option>
< option> C#< / option>
< option> Powershell< / option>
< / select>
接下来,我有一个带文本框的提交按钮。用户可以通过文本框和提交按钮将新选项提交到列表框中。因此,我需要阻止用户在列表框中输入重复的项目。我该怎么办?
以下代码用于将项目添加到列表框中。
< pre style ="color:#000000; font-family:Verdana,Arial,Helvetica,sans-serif; font-size:12px; margin:8px"> function addItem()
{
var lst =的document.getElementById( '列表框'); // listbox control id
var newItem = prompt(" Enter New Item"," Enter Value Here");
//为选项中的每个选项创建选项对象
//新选项([text [,value [,defaultSelected [,selected]]]])//语法
if(newItem == null)
{
return false;
}
else
{
lst.options [lst.length] = new Option(newItem,newItem,false,false);
返回false;
}
}
解决方案
您可以通过两种方式检查重复:
单向:1:循环通过每个项目并将新项目与中的项目进行比较列表。
2.将标志变量设置为"真"。当列表中存在重复并打破循环时。
3。基于标志变量show alert。
双向:
1.检查新项目的索引list对象的innerHTML或innerText属性。
var lst = document.getElementById('listbox');
//存在重复项,索引大于零
if(lst.innerHTML.indexOf(newItem)> 0)
{
//在此处显示提醒。
}其他
{
//添加项目。
}
Hi, I would like to prevent the addition of duplicate items in the following situation.
Firstly, I have a listbox with a few options such as
<select id="listbox" name="listbox" multiple="multiple" style="width: 580px;"> <option>Java</option> <option>PHP</option> <option>Perl</option> <option>Javascript</option> <option>C#</option> <option>Powershell</option> </select>
Next, I have a submit button with a textbox. The user will be able to submit new options into the listbox via the textbox and submit button. Therefore, I need to prevent the user from entering duplicate items into the listbox. How should I do?
The following code is used to add items into the listbox.
function addItem() { var lst = document.getElementById('listbox'); // listbox control id var newItem = prompt("Enter New Item","Enter Value Here"); //Option object is created for every option in a selection //new Option([text[, value[, defaultSelected[, selected]]]]) // Syntax if(newItem == null) { return false; } else { lst.options[lst.length] = new Option(newItem,newItem,false,false); return false; } }
解决方案
You can check duplicates using two ways:
One Way:
1: Loop trough each items and compare the new item with the items in the list.
2. Set a flag variable to "true" when duplicate exists in the list and break the loop.
3. Based on the flag variable show alert.
Two Way:
1.Check the index of new item in the innerHTML or innerText property of list object.
var lst = document.getElementById('listbox');
//duplicate item exists and index will be greater than zero
if(lst.innerHTML.indexOf(newItem) > 0)
{
//show alert here.
}
else
{
// add items.
}
这篇关于防止重复项添加到列表框javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文