Mark13426
Mark13426

Reputation: 2639

Using JQuery, how can I check to see if a dropdown menu contains a value?

Using JQuery, how can I check to see if a dropdown menu contains a value? By value, I don't mean the text displayed as a menu item. I mean the ID (val) of the item. I have a list of items already in the dropdown menu, and I want to add more. Before I do that, I want to make sure I do not duplicate any key-value pairs.

Upvotes: 3

Views: 6088

Answers (3)

Seimen
Seimen

Reputation: 7250

Here is a shortened version of Marc Diethelms solution, without the need of data-attributes: jsfiddle

$('button').bind('click', function() {
    var new_val = $(this).html().split(' ').splice(1).join(' '),
        $sel = '#sel';
    $('option[value='+new_val+']', $sel).length > 0 ?
        alert('nope, exists!') :
        $('<option value="'+ new_val +'">'+new_val+'</option>').appendTo($sel);
});

Upvotes: 0

Marc Diethelm
Marc Diethelm

Reputation: 1202

Something like this will do what you want. (JSFiddle)

html

<select id="sel">
    <option value="foo">foo</option>
</select>
<button data-add="foo">add foo</button>
<button data-add="bar">add bar</button>

js

$('button').on('click', function() {
    var new_val = $(this).data('add');

    if ($('option[value='+new_val+']', '#sel').length) {
        alert('nope, exists!')
    } else {
        $('<option value="'+ new_val +'">'+new_val+'</option>').appendTo( $('#sel') );
    }
});

If you use an older jQuery version than 1.7 use .bind instead of .on.

Upvotes: 3

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

you can try this

  $(document).ready(function () {

  if ($("#drpentry").find("option[value='Dog']:contains('Ds')").length > 0) {

             alert('exist entry');
       }
       else {

           alert('not exist');
       }

   });

check here : http://jsfiddle.net/Eemqh/1/

Upvotes: 0

Related Questions