Modify ↓
Ticket #10422 (closed bug: invalid)
Getting current selected option element from select
| Reported by: | asver@… | Owned by: | |
|---|---|---|---|
| Priority: | undecided | Milestone: | None |
| Component: | unfiled | Version: | 1.6.1 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
I get curent selected option element from select. I can get the current value of select of course, but I want to get the some other attributes of currenty selected option.
<select id="test1">
<option value="-1" tag="0">Select me</option>
<option value="1" tag="a">1</option>
<option value="2" tag="b">2</option>
<option value="3" tag="c">3</option>
<option value="4" tag="d">4</option>
</select>
<a id="go">GO!</a>
<script type="text/javascript">
$(function()
{
$('#go').click(function(){
// This works fine.
console.log($('#test1').val());
// This shows the currently selected element both in prop and attr
$.each($('#test1 option'),function(i,obj){
console.log($(obj).attr('value')+' Attr: '+$(obj).attr('selected')+' Prop: '+$(obj).prop('selected'));
});
// This does not work!
console.log($('#test1 option[selected="selected"]'));
});
});
</script>
Is it a bug, or am I doing something wrong?
Change History
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.
Note: See
TracTickets for help on using
tickets.

This is more of a forum question, but it's a great example of why we added .prop(). The W3C querySelectorAll selector spec pays attention to the selected *attribute* and not the dynamic *property*. For compatibility reasons we return the property when you use .attr() in that case, but it is incorrect usage.
The markup has no option element with a selected attribute, and the user clicking on an element will not create an attribute. Use $("select").val() if you need the selected value. Use $("option").filter(function(){ return this.selected; }) to get the element that is selected.
http://jsfiddle.net/dmethvin/KhkU9/