Skip to main content

Bug Tracker

Side navigation

#10422 closed bug (invalid)

Opened October 05, 2011 07:36AM UTC

Closed October 05, 2011 04:18PM UTC

Getting current selected option element from select

Reported by: asver@wp.pl Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.6.1
Keywords: Cc:
Blocked by: Blocking:
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?

Attachments (0)
Change History (1)

Changed October 05, 2011 04:18PM UTC by dmethvin comment:1

resolution: → invalid
status: newclosed

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/