gpt4 book ai didi

Javascript 验证表单检查文本区域长度

转载 作者:行者123 更新时间:2023-11-30 09:21:15 25 4
gpt4 key购买 nike

我正在研究 Javascript 验证代码以检查评论中的空白字段,每个评论文本区域至少 50 个字符。我从输入的文本中扣除 50,以显示错误弹出消息中剩余的字符。但是,当我打开表单时,我没有输入任何内容,单击提交按钮,只有问题 #2 弹出错误消息“Q#2 - 需要 50 个字符。剩余 50 个字符。问题 #1 应该显示相同的错误消息但它没有。

你能帮帮我吗?

代码如下:

function check() {
var errorMessage = '';

var Q1textLength = document.getElementById('textarea1').value.length;
var Q1text = 50 - Q1textLength
if (Q1textLength < 50)
errorMessage += "Q#1 - 50 character required. " + Q1text + " characters remaining. \n";

var Q2textLength = document.getElementById('textarea2').value.length;
var Q2text = 50 - Q2textLength
if (Q2textLength < 50)
errorMessage = "Q#2 - 50 character required. " + Q2text + " characters remaining. \n";
if (errorMessage) {
alert(errorMessage);
return false;
}
return true;
}
<form action="action.asp" name="frm1" method="Post" />
<fieldset>
<legend>Question 1</legend>
<label for="Comment1">Comments:</label>
<textarea rows="3" cols="85" name="Q1C" id="textarea1" placeholder="Write at least 50 characters" required /></textarea>
</fieldset>

<fieldset>
<legend>Question 2</legend>
<label for="Comment2">Comments:</label>
<textarea rows="3" cols="85" name="Q2C" id="textarea2" placeholder="Write at least 50 characters" required /></textarea>
</fieldset>

<p class="submit"><input type="submit" onClick="return check()" value="Submit"></p>
</form>

最佳答案

因为您在第二个问题中使用相等的 = 覆盖了变量 errorMessage,所以您应该改用 +=

注意:您的 textarea 中有一个额外的斜杠 / 应该删除:

<textarea .... placeholder="Write at least 50 characters" required /></textarea>
___________________________________________________________________^

function check() {
var errorMessage = '';

var Q1textLength = document.getElementById('textarea1').value.length;
var Q1text = 50 - Q1textLength
if (Q1textLength < 50)
errorMessage += "Q#1 - 50 character required. " + Q1text + " characters remaining. \n";

var Q2textLength = document.getElementById('textarea2').value.length;
var Q2text = 50 - Q2textLength
if (Q2textLength < 50)
errorMessage += "Q#2 - 50 character required. " + Q2text + " characters remaining. \n";
if (errorMessage) {
alert(errorMessage);
return false;
}
return true;
}
<form action="action.asp" name="frm1" method="Post" />
<fieldset>
<legend>Question 1</legend>
<label for="Comment1">Comments:</label>
<textarea rows="3" cols="85" name="Q1C" id="textarea1" placeholder="Write at least 50 characters" required></textarea>
</fieldset>

<fieldset>
<legend>Question 2</legend>
<label for="Comment2">Comments:</label>
<textarea rows="3" cols="85" name="Q2C" id="textarea2" placeholder="Write at least 50 characters" required></textarea>
</fieldset>

<p class="submit"><input type="submit" onClick="return check()" value="Submit"></p>
</form>

关于Javascript 验证表单检查文本区域长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51481883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com