Prevent Duplicate Entries in a HTML DropDown

I was recently asked a question on the ASP.NET forum on how to prevent duplicate entries being added to a select form element. The user could type anything into a text box, then click the button and it was being added. This is another good use for jQuery! Here's the code.

<html>
<
head>
<
script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function(e) {
var itemExists = false;
var txt = $("#Text1").val();
e.preventDefault();
$("#Select1 option").each(function() {
if ($(this).text() == $.trim(txt)) {
itemExists = true;
alert('Item already exists');
}
});

if (!itemExists) {
$("#Select1").append("<option value=\"1\">" + txt + "</option>");
$("#Text1").val('');
}
});
});
</script>
</
head>
<
body>
<
form>
<
input id="Button1" type="button" value="Add" /><br />
<
input id="Text1" type="text" />
<
select id="Select1">
<
option value="1">Yahoo</option>
<
option value="2">Microsoft</option>
<
option value="3">Google</option>
</
select>
</
form>
</
body>
</
html>



Now duplicate items are not added.

Note: To ignore case, use .toLowerCase() or .toUpperCase() to compare both strings.

See a Live Demo

No comments:

Post a Comment