Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Is there some way to make val() return an empty string instead of 'undefined' for an empty list?

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 ''.

like image 882
Chris Avatar asked Dec 21 '10 00:12

Chris


3 Answers

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

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

like image 110
SLaks Avatar answered Sep 28 '22 15:09

SLaks


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

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

like image 28
Sujit Senapati Avatar answered Sep 28 '22 14:09

Sujit Senapati


How about:

var x = $('#my-textbox-id').hasClass("watermark") ? "" : $('#my-textbox-id').val();
like image 21
karim79 Avatar answered Sep 28 '22 15:09

karim79