tags:

views:

43

answers:

2

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?

UPDATE:

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?

+2  A: 

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.

ryangavin
I agree, this is the right way to do it. +1 (even though my answer directly answers the OP's question)
Jamiec
A: 

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/

Jamiec
Thank so much, i will look into it and in the mean time i have one more similar question http://stackoverflow.com/questions/3335533/add-item-from-dropdownlist-to-listbox-using-jquery
Abu Hamzah
i have update my question, please have a look at it.
Abu Hamzah
@Nisar Khan - My solution above works if you have added the items in codebehind as well. All the `var $result = ...` line does is looks for an item in the result list which already has a value of the selected option from the `#items` list.
Jamiec
+1 thanks so much.
Abu Hamzah