5

With Jquery, is there some way to make val() return an empty string instead of 'undefined' when called against an empty list of elements?

E.g., I have this code:

var x = $('#my-textbox-id').not('.watermark').val();

The idea is that I want to get the value of my textbox, but I want an empty string if it is currently showing the watermark (i don't want the watermark value!).

The selector works, but i don't want 'undefined' - I want an empty string ''.

jm.
  • 23,422
  • 22
  • 79
  • 93
Chris
  • 39,719
  • 45
  • 189
  • 235

4 Answers4

13

You can write (...).val() || "".

Only use this for text fields; it will also replace false or the number 0 with "".

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Or you can use $.trim to get the expected result.

Example: $.trim($('#my-textbox-id').not('.watermark').val())

Pedram
  • 6,256
  • 10
  • 65
  • 87
1

How about:

var x = $('#my-textbox-id').hasClass("watermark") ? "" : $('#my-textbox-id').val();
karim79
  • 339,989
  • 67
  • 413
  • 406
0
var x = $('#my-textbox-id').not('.watermark').val() == undefined 
? '' 
: $('#my-textbox-id').not('.watermark').val();
Arvin
  • 1,210
  • 2
  • 15
  • 18