Tutorial :how to prevent duplicate item


i have a dropdownlist (asp.net control) and a listbox control and a Add button when the user select the item from dropdownlist and click on add button to add to the listbox.

how can i prevent the user from adding duplciate items and alert saying its already in the listbox?


in my particular scenario, i have a dropdwonlist and adding the item to listbox both are asp.net controls and i am adding the items from code-behind and your solution is pure on client side, is there a way i can read the listbox and compare and alert the message?


Pretty easy. With this simple markup:

<select id="items">      <option>One</option>      <option>Two</option>      <option>Three</option>  </select>  <input type="button" id="add" value="Add" />  <select id="result" multiple="multiple" size="5">  </select>  

This would be the jQuery:

$('#add').click(function(){      var item = $('#items').val();      var $result = $('#result>option[value="' + item + '"]');      if($result.length == 0){          $('#result').append('<option value="' + item + '">' + item + '</option>');      }      else{         alert('The item "' + item + '" has already been added');        }  });  

Check the fiddle: http://jsfiddle.net/mKFzz/

Edit: If you want to do it as per @ryangavin's suggestion, here is the fiddle: http://jsfiddle.net/baLZN/


One way is to remove the item form the dropdownlist after it's added, that way the user can't even select it a second time. Removes the need for annoying alerts.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »