jQuery 检查文本框是否有空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1565193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:44:18  来源:igfitidea点击:

Check if textbox has empty value

jquery

提问by KJai

I have the following code:

我有以下代码:

var inp = $("#txt");

if(inp.val() != "")
// do something

Is there any other way to check for empty textbox using the variable 'inp'

有没有其他方法可以使用变量“inp”检查空文本框

回答by wiifm

if (inp.val().length > 0) {
    // do something
}

if you want anything more complicated, consider regex or use the validation pluginwhich takes care of this for you

如果您想要更复杂的东西,请考虑使用正则表达式或使用为您处理此问题的验证插件

回答by Grimmy

var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
   //do something
}

Removes white space before checking. If the user entered only spaces then this will still work.

检查前删除空格。如果用户只输入空格,那么这仍然有效。

回答by rahul

if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

当文本框中的空格字符超过 1 个时,您的方法将失败。

回答by KAPIL SHARMA

Use the following to check if text box is empty or have more than 1 white spaces

使用以下命令检查文本框是否为空或有超过 1 个空格

var name = jQuery.trim($("#ContactUsName").val());

if ((name.length == 0))
{
    Your code 
}
else
{
    Your code
}

回答by Tod

$('input:text').filter(function() { return this.value.length > 0; });

回答by Ricky Odin Matthews

if ( $("#txt").val().length == 0 )
{
  // do something
}

I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.

我必须添加 == 才能让它为我工作,否则即使输入空文本也会忽略条件。可能会帮助某人。

回答by Software Engineer

Also You can use

你也可以使用

$value = $("#txt").val();

if($value == "")
{
    //Your Code Here
}
else
{
   //Your code
}

Try it. It work.

尝试一下。这行得通。

回答by simhumileco

The check can be done like this:

检查可以这样完成:

if (!!inp.val()) {

}

and even shorter:

甚至更短:

if (inp.val()) {

}