Using JQuery, how can I check if the dropdown menu contains a value?
Using JQuery, how can I check if the dropdown menu contains a value? By meaning, I don't mean the text displayed as a menu item. I mean the id (val) of the element. I have a list of items already in the dropdown and I want to add more. Before I do that, I want to make sure I don't duplicate key pairs.
+3
source to share
3 answers
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 are using an older version of jQuery than 1.7, use .bind
instead .on
.
+3
source to share
Here is a shortened version of Marc Diethelms solution without 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);
});
0
source to share