How to get attribute from selected option of select in jQuery?
Asked Answered
P

2

12

I have the next selectbox in HTML:

<select id="listbox-taskStatus" class="selectpicker">
    <option status="0">In progress</option>
    <option status="1">Not started</option>
    <option status="2">Done</option>
    <option status="3">Failed</option>
</select>

I want to read the attribute value from selected option.

If just to take the value, it's simple:

var value = $('#listbox-taskStatus').val();

But what should I do, if I want to get the attribute value from selected option? I know, that .attr() must help, but when I tried to use it I've got the incorrect result.

I've tried the next:

var status = $('#listbox-taskStatus option').attr('status');

But the returned value is always 0 despite on fact I was selecting different option.

What's wrong, how to solve my problem?

Plica answered 21/8, 2014 at 15:44 Comment(2)
$('#listbox-taskStatus option') gets all of the option elements. You just want the selected one.Repurchase
@undefined , because it's not value. Even jQuery have made special function .val() fro getting values from DOM elements, and the value of <option> is inside its tag. So as for me I can't name the attribute as value, but it's my own opinion. Of course it's a vexed question, but I think it's some freedom for naming the attributes.Plica
C
38

Use :selected Selector

var status = $('#listbox-taskStatus option:selected').attr('status');

However, I would recommend you to use data- prefixed attribute. Then you can use .data()

var status = $('#listbox-taskStatus option:selected').data('status');

DEMO

Carmon answered 21/8, 2014 at 15:45 Comment(0)
N
-1
var optionAttr1 = $('#listbox-taskStatus').find('option:selected').attr("status");
var optionAttr = $('#listbox-taskStatus option:selected').attr("status");
Numeral answered 1/6, 2022 at 8:37 Comment(1)
A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation.Robertroberta

© 2022 - 2024 — McMap. All rights reserved.