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

With jquery, is there a way to make val () return an empty string instead of 'undefined' when called with an empty list of elements?

For example, I have this code:

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

The idea is that I want to get the value of my text box, but I want an empty string if the watermark is currently displayed (I don't want the watermark value!).

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

+3
source share
4 answers

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

; false 0 "".

+9

:

var x = $('#my-textbox-id').hasClass("watermark") ? "" : $('#my-textbox-id').val();
+1

Or you can use $.trimto get the expected result.

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

+1
source
var x = $('#my-textbox-id').not('.watermark').val() == undefined 
? '' 
: $('#my-textbox-id').not('.watermark').val();
0
source

Source: https://habr.com/ru/post/1765875/


All Articles