javascript 检查 textarea 是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14455728/
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
check whether a textarea is empty
提问by suhas
Can anyone please tell me what the problem is with this code:
谁能告诉我这段代码有什么问题:
function c(id)
{
var empty = document.getElementById(id);
if(empty.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
This is my html code:
这是我的 html 代码:
<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>
回答by Kevin Bowersox
The value property of the textarea should be checked to determine if it is empty.
应检查 textarea 的 value 属性以确定它是否为空。
var content = document.getElementById(id).value;
if(content.length<1)
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
Working Example: http://jsfiddle.net/35DFR/2/
工作示例:http: //jsfiddle.net/35DFR/2/
回答by Gjordis
if (YOURFORM.YOURTEXTFIELDVARIABLENAME.value == "")
{
return True
}
回答by skub
Try this:
试试这个:
function c(id)
{
if(document.getElementById(id).value == '')
{
window.alert ("This field cant be left empty");
return true;
}
else
{
return false;
}
}
If you want to go a bit further, you might want to trim the value first though.
如果您想更进一步,您可能需要先修剪该值。
Update:
更新:
From the comments, try changing the 'onchange' to 'onkeyup':
从评论中,尝试将“ onchange”更改为“ onkeyup”:
<textarea rows="3" cols="80" id="ta1" onkeyup="c('ta1');"></textarea>
回答by wildpea
function c(id) {
var empty =document.getElementById(id);
if(!empty.value){
window.alert("This field cant be left empty");
return true;
}else{
return false;
}
}
try this
试试这个