我有一个包含 2 个文本区域的页面,如果在单击提交按钮时键入的字符超过最大长度,我想验证每个文本区域。下面的代码有问题 单击提交时,它只能检测 textarea1 是否超过最大长度,而不能检测其他文本区域。我想做的是它可以确定哪个文本区域超过了最大长度,以便用户可以更正它。提前致谢。
<html>
<head>
<script>
function testing()
{
var txtlength=document.getElementById("txt1").value.length;
if(txtlength>50)
{
alert("Max1 length reached ");
return false;
}
else
{
return true;
}
var txtlength1=document.getElementById("txt2").value.length;
if(txtlength1>50)
{
alert("Max2 length reached ");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form action="test1.html" method="post" onsubmit="return testing();">
<textarea id="txt1"></textarea>
<textarea id="txt2"></textarea>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
最佳答案
return true
语句应该只在代码末尾执行一次。
最终代码应该是这样的:
<script>
function testing()
{
var txtlength=document.getElementById("txt1").value.length;
if(txtlength>50)
{
alert("Max1 length reached ");
return false;
}
var txtlength1=document.getElementById("txt2").value.length;
if(txtlength1>50)
{
alert("Max2 length reached ");
return false;
}
return true;
}
</script>
关于javascript - 验证javascript中的多个文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897563/