Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if html select contains a value in any of its child options

Tags:

jquery

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?

like image 950
Dan Avatar asked Jun 30 '10 12:06

Dan


People also ask

How do I know which option is selected in HTML?

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

How do I know which option is selected in dropdown?

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.

How do you style the option of an HTML select element?

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?

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


1 Answers

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;
}
like image 95
Nick Craver Avatar answered Oct 14 '22 11:10

Nick Craver