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.
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.
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.
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").
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.
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');
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