From: ruado1987 Date: Sun, 3 Mar 2013 15:51:04 +0000 (+0800) Subject: Fix #13514: Set selectedIndex to -1 when non-matching value is set on a select. Close... X-Git-Tag: 2.0.0-beta3~48 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=c9ca9bf509edd1dc0a92564210f3f325cc7555b6;p=jquery.git Fix #13514: Set selectedIndex to -1 when non-matching value is set on a select. Close gh-1191. (cherry picked from commit 48d71d0c3e53d1bb1688fc6c0593b008ced3403b) --- diff --git a/src/attributes.js b/src/attributes.js index c9e7dbc47..37addf4a2 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -272,13 +272,20 @@ jQuery.extend({ }, set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { + optionSet = true; + } + } + + // force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { elem.selectedIndex = -1; } return values; diff --git a/test/unit/attributes.js b/test/unit/attributes.js index 7d0366b90..5996ce15c 100644 --- a/test/unit/attributes.js +++ b/test/unit/attributes.js @@ -846,6 +846,22 @@ test( "val()", function() { equal( jQuery("