Given a select
<select id="Myselect">
<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?
The selectedIndex property sets or returns the index of the selected option in a drop-down list. The index starts at 0. Note: If the drop-down list allows multiple selections it will only return the index of the first option selected. Note: The value "-1" will deselect all options (if any).
The selectedIndex property returns the index of the currently selected element in the dropdown list. This index starts from 0 and returns -1 if no option is selected. The options property returns the collection of all the option elements in the <select> dropdown list.
You can use inline styles to add custome styling to <option> tags. For eg : <option style="font-weight:bold;color:#09C;">Option 1</option> This will apply the styles to this particular <option> element only.
How can I check whether a option already exist in select by jQuery? Check this: var IsExists = false; $('#ddlCity option').
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;
}
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