Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...