Html 检查文本框是否在Javascript中为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19862344/
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
Checking textbox if it's empty in Javascript
提问by Zach Brantmeier
I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
我写了一个带有文本框和提交按钮的简单 html 文件,它会根据您提交的内容生成和 document.write 的响应。我想让它生成一个响应,说如果框为空则输入内容。文本框的id是chatinput,所以我在开头有以下代码
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
然后有一个条件,虽然我不能让它正常工作;我试过了
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?
和其他人,但没有一个工作正常。有没有人有其他想法?
回答by
It should be this:
应该是这样的:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
或简写:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The =
assigns a value whereas ==
checks whether the values are equal.
的=
分配值,而==
检查该值是否相等。
回答by PlantTheIdea
Just offering an alternative, not trying to steal thunder ...
只是提供一个替代方案,而不是试图窃取风声......
Create an isEmpty
function to reuse on a variety of items.
创建一个isEmpty
函数以在各种项目上重复使用。
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
然后你可以将它应用到你想要的任何元素:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.
不完全是原创,它的概念是从 PHP 中偷来的,但它派上用场了很多。