最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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

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

Share Improve this question edited Dec 21, 2010 at 0:56 jm. 23.7k23 gold badges81 silver badges93 bronze badges asked Dec 21, 2010 at 0:42 ChrisChris 40.6k46 gold badges195 silver badges239 bronze badges 1
  • 1 var x = $('#my-textbox-id').not('.watermark').val() || ''; – qwertymk Commented Dec 21, 2010 at 1:02
Add a ment  | 

4 Answers 4

Reset to default 13

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

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

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

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

How about:

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论