简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM