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")
How can I check whether a option already exist in select by jQuery? Check this: var IsExists = false; $('#ddlCity option').
var exists = $("#yourSelect option") . filter(function (i, o) { return o. value === yourValue; }) .
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.
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).
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';
});
The jQuery filter function accepts a function as its argument:
$('#sel option').filter(function() {
return $(this).text() === "Option1";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With