Make .val(undefined) == .val("") and chainable; fixes #4130.

Ensure .val(null) sets an empty string on IE6/7; fixes #5163.
This commit is contained in:
dmethvin 2010-08-21 10:32:34 +08:00 committed by John Resig
parent c4e653237f
commit 0636dffc24
2 changed files with 12 additions and 5 deletions

View file

@ -136,7 +136,7 @@ jQuery.fn.extend({
}, },
val: function( value ) { val: function( value ) {
if ( value === undefined ) { if ( !arguments.length ) {
var elem = this[0]; var elem = this[0];
if ( elem ) { if ( elem ) {
@ -209,9 +209,10 @@ jQuery.fn.extend({
val = value.call(this, i, self.val()); val = value.call(this, i, self.val());
} }
// Typecast each time if the value is a Function and the appended // Treat null/undefined as ""; convert numbers to string
// value is therefore different each time. if ( val == null ) {
if ( typeof val === "number" ) { val = "";
} else if ( typeof val === "number" ) {
val += ""; val += "";
} }

View file

@ -359,14 +359,20 @@ test("val()", function() {
}); });
var testVal = function(valueObj) { var testVal = function(valueObj) {
expect(6); expect(8);
jQuery("#text1").val(valueObj( 'test' )); jQuery("#text1").val(valueObj( 'test' ));
equals( document.getElementById('text1').value, "test", "Check for modified (via val(String)) value of input element" ); equals( document.getElementById('text1').value, "test", "Check for modified (via val(String)) value of input element" );
jQuery("#text1").val(valueObj( undefined ));
equals( document.getElementById('text1').value, "", "Check for modified (via val(undefined)) value of input element" );
jQuery("#text1").val(valueObj( 67 )); jQuery("#text1").val(valueObj( 67 ));
equals( document.getElementById('text1').value, "67", "Check for modified (via val(Number)) value of input element" ); equals( document.getElementById('text1').value, "67", "Check for modified (via val(Number)) value of input element" );
jQuery("#text1").val(valueObj( null ));
equals( document.getElementById('text1').value, "", "Check for modified (via val(null)) value of input element" );
jQuery("#select1").val(valueObj( "3" )); jQuery("#select1").val(valueObj( "3" ));
equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" ); equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" );