我正在研究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>
答案 0 :(得分:3)
那是因为您要在第二个问题中使用相等的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>
答案 1 :(得分:1)
更改此
errorMessage = errorMessage+ "Q#2 - 50 character required. " + Q2text + " characters remaining. \n";
if(errorMessage)