Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an select option exists based on text in jQuery 1.7

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")

like image 218
yz10 Avatar asked Jul 24 '12 20:07

yz10


People also ask

How can I check whether a option already exist in select by jQuery?

How can I check whether a option already exist in select by jQuery? Check this: var IsExists = false; $('#ddlCity option').

How can I check whether a option already exist in select by JavaScript?

var exists = $("#yourSelect option") . filter(function (i, o) { return o. value === yourValue; }) .

Is there a select event in jQuery?

jQuery select() MethodThe select event occurs when a text is selected (marked) in a text area or a text field. The select() method triggers the select event, or attaches a function to run when a select event occurs.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

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';
});
like image 126
undefined Avatar answered Sep 19 '22 13:09

undefined


The jQuery filter function accepts a function as its argument:

$('#sel option').filter(function() { 
    return $(this).text() === "Option1"; 
});
like image 31
Christian Mann Avatar answered Sep 17 '22 13:09

Christian Mann