jQuery 检查输入值是否为空或默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15259170/
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 14:40:52  来源:igfitidea点击:

Checking if input value is not empty or default

javascriptjquery

提问by Linas

I'm look for an elegant way to check if input value is not empty and not default.

我正在寻找一种优雅的方法来检查输入值是否不为空且不是默认值。

For example let's say we have input with value Username, this is a default value, and once the user clicks on this input field Usernamewould be deleted so user could enter what he wants. Just to make it clear this is how it would look when the page is loaded:

例如,假设我们输入了 value Username,这是一个默认值,一旦用户单击此输入字段Username将被删除,因此用户可以输入他想要的内容。只是为了说明这是加载页面时的样子:

<input type="text" class="defaultValue" value="Username" />

<input type="text" class="defaultValue" value="Username" />

Now by default this field would never be empty, unless user would do something to make it empty, so just to make sure i need to check for both things. The way i would do this is very simple:

现在默认情况下这个字段永远不会是空的,除非用户会做一些事情来使它空,所以只是为了确保我需要检查这两件事。我这样做的方法很简单:

if($(".defaultValue").val().length == 0 || $(".defaultValue").val() == "Username")
   alert("Please enter your username");

So this works, but looks ugly as hell. And usually i need to deal with huge forms so my code gets really ugly and hard to manage because of this, any way to improve this?

所以这有效,但看起来很丑。通常我需要处理巨大的表单,因此我的代码变得非常丑陋且难以管理,有什么办法可以改进吗?

Thanks.

谢谢。

回答by RobG

Try:

尝试:

if (this.value == '' || this.value == this.defaultValue) {
  // value is empty or is default value
}

回答by Amy

Try writing a helper function to do this check for you.

尝试编写一个辅助函数来为您执行此检查。

var isEmptyOrDefault = function(field, default) {
    var value = $(field).val();
    return (value.length === 0 || value === default);
};

So you can use it:

所以你可以使用它:

if (isEmptyOrDefault($('.defaultValue'), 'Username')) {
    alert("Please enter your username");
}