Skip to content

Commit

Permalink
Make .val(undefined) == .val("") and chainable; fixes #4130.
Browse files Browse the repository at this point in the history
Ensure .val(null) sets an empty string on IE6/7; fixes #5163.
  • Loading branch information
dmethvin authored and jeresig committed Sep 24, 2010
1 parent c4e6532 commit 0636dff
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/attributes.js
Expand Up @@ -136,7 +136,7 @@ jQuery.fn.extend({
},

val: function( value ) {
if ( value === undefined ) {
if ( !arguments.length ) {
var elem = this[0];

if ( elem ) {
Expand Down Expand Up @@ -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 += "";
}

Expand Down
8 changes: 7 additions & 1 deletion test/unit/attributes.js
Expand Up @@ -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" );

Expand Down

0 comments on commit 0636dff

Please sign in to comment.