Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a <select> element on the basis of selected option text?

Suppose there are many <select> elements in a form. I need a selector that selects a <select> element whose selected option has certain text. To explain, let's say there are 5 <select> elements of class "color". Each of them have 3 <option> with texts "white", "black", "green". Now I need to select the elements whose selected option is "white".

<select class="color" > 
  <option value=""></option>
  <option value="1"> white </option>
  <option value="2"> black </option>
  <option value="2"> green </option>
</select>

In the scenario as depicted in the below image, I need to select those two white <select>s.

enter image description here

Thanks.

like image 559
Manoj Shrestha Avatar asked Sep 13 '13 06:09

Manoj Shrestha


People also ask

How do I get selected text option in select?

Use the selectedIndex Property We can get the index of the selected item with the selectedIndex property. Then we can use the text property to get the text of the selected item. We create the getSelectedText function that takes an element as the parameter. Then we check if selectedIndex is -1.

How do you get the selected value of an element?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do you select option by value?

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute.


1 Answers

Try

$('select.color option:contains(white)').prop('selected','selected');

DEMO

Select all the elements whose selected option is "white".

Updated DEMO

$('select.color option:contains(white):selected').parent('select');

Match Exact value

DEMO

$('select.color option:contains(white):selected').each(function(){
    if($(this).text() == 'white'){
        $(this).parent('select').css('color','blue');
    }
});
like image 178
Tushar Gupta - curioustushar Avatar answered Oct 06 '22 00:10

Tushar Gupta - curioustushar