Determine if html select contains a value in any of its child options
Given a select
<select id="Mys开发者_C百科elect">
<option value="-1">Please Select<option>
<option value="1">Selection 1<option>
<option value="2">Selection 2<option>
</select>
What the best way to determine if there is an option of value X in the select with JQuery?
You can do this using a selector and .length
, like this:
var exists = $("#mySelect option[value='-1']").length !== 0;
Or as a function:
function optionExists(val) {
return $("#mySelect option[value='" + val + "']").length !== 0;
}
If it's not numbers and you may have '
in there for example (screwing the selector), you can use .filter()
, like this:
function optionExists(val) {
return $("#mySelect option").filter(function() {
return this.value === val;
}).length !== 0;
}
The :has() selector should work, something like this:
var exists = $("#Myselect:has(option[value='X'])").length > 0;
This is far from the only way, but an easy to understand approach.
You could also do somethi.g like this for an .Exists() function since .length > 0
is sometimes not clear to mean it does exist.
精彩评论