Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find select options attributes

I know how to get the attributes of an element, using jquery. But I'm not sure how to do it with the actual options in a select field.

<select referenceID="55" name="test" id="test">
  <option value="1">first option</option>
  <option value="2">second option</option>
  <option value="3">third option</option>
</select>

To get the referenceID I would just do this:

$("#test").attr("referenceID");

And when I want to get the value:

$("#test").val();

But I want to get a little more interesting. I want to put some specific info into each option:

<select name="test" id="test">
  <option value="1" title="something here"*>first option</option>
  <option value="2" title="something else here">second option</option>
  <option value="3" title="another thing here">third option</option>
</select>

Is it possible to grab an attribute within the options tags?

I intend to have an onselect function that reads the title tag, and does helps me with some other things.

like image 262
coffeemonitor Avatar asked Jun 01 '11 22:06

coffeemonitor


People also ask

How can check select option selected or not in jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do I get the text value of a selected option jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do I get a dropdown selected value?

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.


1 Answers

Presuming you want to find the title attribute of the selected option...

$('#test option:selected').attr('title');

That is, find the descendant element of #test that is (a) an option element and (b) is selected.

If you already have a selection containing #test, you can do this with find:

$('#test').find('option:selected').attr('title');
like image 192
lonesomeday Avatar answered Sep 21 '22 05:09

lonesomeday