From 0636dffc2481c14368464a22ffa1bd8017da2a26 Mon Sep 17 00:00:00 2001 From: dmethvin Date: Sat, 21 Aug 2010 10:32:34 +0800 Subject: [PATCH] Make .val(undefined) == .val("") and chainable; fixes #4130. Ensure .val(null) sets an empty string on IE6/7; fixes #5163. --- src/attributes.js | 9 +++++---- test/unit/attributes.js | 8 +++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/attributes.js b/src/attributes.js index a76695b6..fd3e38ac 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -136,7 +136,7 @@ jQuery.fn.extend({ }, val: function( value ) { - if ( value === undefined ) { + if ( !arguments.length ) { var elem = this[0]; if ( elem ) { @@ -209,9 +209,10 @@ jQuery.fn.extend({ val = value.call(this, i, self.val()); } - // Typecast each time if the value is a Function and the appended - // value is therefore different each time. - if ( typeof val === "number" ) { + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { val += ""; } diff --git a/test/unit/attributes.js b/test/unit/attributes.js index 986623b4..3326dfe8 100644 --- a/test/unit/attributes.js +++ b/test/unit/attributes.js @@ -359,14 +359,20 @@ test("val()", function() { }); var testVal = function(valueObj) { - expect(6); + expect(8); jQuery("#text1").val(valueObj( 'test' )); 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 )); 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" )); equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" );