Skip to content

Commit b188947

Browse files
committed
Attributes: fix setting selected on an option in IE<=11
Fixes jquerygh-2732 Close jquerygh-2840
1 parent 63317eb commit b188947

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/attributes/prop.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,11 @@ if ( !support.hrefNormalized ) {
100100
}
101101

102102
// Support: Safari, IE9+
103-
// mis-reports the default selected property of an option
104-
// Accessing the parent's selectedIndex property fixes it
103+
// Accessing the selectedIndex property
104+
// forces the browser to respect setting selected
105+
// on the option
106+
// The getter ensures a default option is selected
107+
// when in an optgroup
105108
if ( !support.optSelected ) {
106109
jQuery.propHooks.selected = {
107110
get: function( elem ) {
@@ -116,6 +119,16 @@ if ( !support.optSelected ) {
116119
}
117120
}
118121
return null;
122+
},
123+
set: function( elem ) {
124+
var parent = elem.parentNode;
125+
if ( parent ) {
126+
parent.selectedIndex;
127+
128+
if ( parent.parentNode ) {
129+
parent.parentNode.selectedIndex;
130+
}
131+
}
119132
}
120133
};
121134
}

test/unit/attributes.js

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

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

0 commit comments

Comments
 (0)