Skip to content

Commit 67d4aeb

Browse files
committed
Attributes: fix setting selected on an option in IE<=11
Fixes jquerygh-2732 Close jquerygh-2840
1 parent 63397aa commit 67d4aeb

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/attributes/prop.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ jQuery.extend( {
7979
}
8080
} );
8181

82+
// Support: IE <=11 only
83+
// Accessing the selectedIndex property
84+
// forces the browser to respect setting selected
85+
// on the option
86+
// The getter ensures a default option is selected
87+
// when in an optgroup
8288
if ( !support.optSelected ) {
8389
jQuery.propHooks.selected = {
8490
get: function( elem ) {
@@ -87,6 +93,16 @@ if ( !support.optSelected ) {
8793
parent.parentNode.selectedIndex;
8894
}
8995
return null;
96+
},
97+
set: function( elem ) {
98+
var parent = elem.parentNode;
99+
if ( parent ) {
100+
parent.selectedIndex;
101+
102+
if ( parent && parent.parentNode ) {
103+
parent.parentNode.selectedIndex;
104+
}
105+
}
90106
}
91107
};
92108
}

test/unit/attributes.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,37 @@ QUnit.test( "prop('tabindex', value)", function( assert ) {
785785
assert.equal( clone[ 0 ].getAttribute( "tabindex" ), "1", "set tabindex on cloned element" );
786786
} );
787787

788+
QUnit.test( "option.prop('selected', true) affects select.selectedIndex (gh-2732)", function( assert ) {
789+
assert.expect( 2 );
790+
791+
function addOptions( $elem ) {
792+
return $elem.append(
793+
jQuery( "<option/>" ).val( "a" ).text( "One" ),
794+
jQuery( "<option/>" ).val( "b" ).text( "Two" ),
795+
jQuery( "<option/>" ).val( "c" ).text( "Three" )
796+
)
797+
.find( "[value=a]" ).prop( "selected", true ).end()
798+
.find( "[value=c]" ).prop( "selected", true ).end();
799+
}
800+
801+
var $optgroup,
802+
$select = jQuery( "<select/>" );
803+
804+
// Check select with options
805+
addOptions( $select ).appendTo( "#qunit-fixture" );
806+
$select.find( "[value=b]" ).prop( "selected", true );
807+
assert.equal( $select[ 0 ].selectedIndex, 1, "Setting option selected affects selectedIndex" );
808+
809+
$select.empty();
810+
811+
// Check select with optgroup
812+
$optgroup = jQuery( "<optgroup/>" );
813+
addOptions( $optgroup ).appendTo( $select );
814+
$select.find( "[value=b]" ).prop( "selected", true );
815+
816+
assert.equal( $select[ 0 ].selectedIndex, 1, "Setting option in optgroup selected affects selectedIndex" );
817+
} );
818+
788819
QUnit.test( "removeProp(String)", function( assert ) {
789820
assert.expect( 6 );
790821
var attributeNode = document.createAttribute( "irrelevant" ),

0 commit comments

Comments
 (0)