6

So I have the following piece of HTML:

<select id="sel">
<option value="0">Option1</option>
<option value="1">Option2</option>
<option value="2">Option3</option>
<option value="3">Option4</option>
</select>

How do I check to see if #sel has an option based on the text value? ("Option1")

yz10
  • 721
  • 3
  • 8
  • 12
  • Found this past question that should provide assistance to your problem [Possible Solution](http://stackoverflow.com/questions/2385963/how-do-i-check-if-no-option-is-selected-in-a-selectbox-using-jquery) – Ryan Beaulieu Jul 24 '12 at 20:50

4 Answers4

15

Try the following:

var opt = 'Option1';
if ($('#sel option:contains('+ opt +')').length) {
   alert('This option exists')
}

Demo

edit: The above snippet uses the jQuery contains selector which filters elements that their textContent contains the specified value. For an exact match you can use the code snippet suggested in christian-mann's answer.

How to do this with Javascript (not jquery) – Jerry

var optionExists = [].some.call(document.getElementById('sel').options, function(option) {
   return option.textContent === 'value';
});
Ram
  • 143,282
  • 16
  • 168
  • 197
9

The jQuery filter function accepts a function as its argument:

$('#sel option').filter(function() { 
    return $(this).text() === "Option1"; 
});
Christian Mann
  • 8,030
  • 5
  • 41
  • 51
1
var length = $('#sel option').filter(function() { 
    return $(this).text() === "Option1"; 
}).length;

if(length == 0)
    console.log('This option text doesn't exist.');
else
    console.log('This option text exists ' + length + ' times.');

If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.

triplethreat77
  • 1,276
  • 8
  • 34
  • 69
0
var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false
adeneo
  • 312,895
  • 29
  • 395
  • 388