Skip to content

Commit 43b06cf

Browse files
committed
Make .val(undefined) == .val("") and chainable; fixes jquery#4130.
Ensure .val(null) sets an empty string on IE6/7; fixes jquery#5163.
1 parent 5c7d5d3 commit 43b06cf

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/attributes.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ jQuery.fn.extend({
134134
},
135135

136136
val: function( value ) {
137-
if ( value === undefined ) {
137+
if ( !arguments.length ) {
138138
var elem = this[0];
139139

140140
if ( elem ) {
@@ -204,9 +204,10 @@ jQuery.fn.extend({
204204
val = value.call(this, i, self.val());
205205
}
206206

207-
// Typecast each time if the value is a Function and the appended
208-
// value is therefore different each time.
209-
if ( typeof val === "number" ) {
207+
// Treat null/undefined as ""; convert numbers to string
208+
if ( val == null ) {
209+
val = "";
210+
} else if ( typeof val === "number" ) {
210211
val += "";
211212
}
212213

test/unit/attributes.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,14 +361,20 @@ test("val()", function() {
361361
});
362362

363363
var testVal = function(valueObj) {
364-
expect(6);
364+
expect(8);
365365

366366
jQuery("#text1").val(valueObj( 'test' ));
367367
equals( document.getElementById('text1').value, "test", "Check for modified (via val(String)) value of input element" );
368368

369+
jQuery("#text1").val(valueObj( undefined ));
370+
equals( document.getElementById('text1').value, "", "Check for modified (via val(undefined)) value of input element" );
371+
369372
jQuery("#text1").val(valueObj( 67 ));
370373
equals( document.getElementById('text1').value, "67", "Check for modified (via val(Number)) value of input element" );
371374

375+
jQuery("#text1").val(valueObj( null ));
376+
equals( document.getElementById('text1').value, "", "Check for modified (via val(null)) value of input element" );
377+
372378
jQuery("#select1").val(valueObj( "3" ));
373379
equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" );
374380

0 commit comments

Comments
 (0)