Skip to content

Commit 780cac8

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

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
@@ -796,6 +796,37 @@ QUnit.test( "prop('tabindex', value)", function( assert ) {
796796
assert.equal( clone[ 0 ].getAttribute( "tabindex" ), "1", "set tabindex on cloned element" );
797797
} );
798798

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

0 commit comments

Comments
 (0)