gpt4 book ai didi

单击“提交”后,JavaScript 验证错误消息没有消失

转载 作者:行者123 更新时间:2023-12-03 04:54:27 26 4
gpt4 key购买 nike

下面的代码验证具有两个字段的表单。当我在没有任何数据的情况下单击提交按钮时,错误消息会显示哪个工作正常,但如果我在之后输入数据并单击提交按钮,错误消息不会消失。

<script>
function validateForm() {
var valid = true;
var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}

var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}

return valid;

}
</script>
</head>
<body>
<form action="#" method="post" name="myForm" onsubmit=" return validateForm()">
<div>
<label for="myActivityName">*Activity Name:</label>
<input type="text" name="activityName" value="" placeholder="Enter Activity Name" />
<p id="activityName"></p>
</div><br>

<div>
<label for="reporter">*Reporter:</label>
<input type="text" name="reporter" value="" placeholder="Enter Reporter " />
<p id="reporter"></p>
</div><br>
<input type="submit" value="Submit" >
</form>
</body>

最佳答案

另一个答案是正确的,但这里有一些代码来支持它。请注意,activityNamereporterinnerHTML 在验证发生之前都会(重新)设置回空:

function validateForm() {
var valid = true;
document.getElementById("activityName").innerHTML = "";
document.getElementById("reporter").innerHTML = "";

var x = document.forms["myForm"]["activityName"].value;
if (x == "" || x == null) {
document.getElementById("activityName").innerHTML = "Please Enter Activity Name";
valid= false;
}

var r = document.forms["myForm"]["reporter"].value;
if (r == "") {
document.getElementById("reporter").innerHTML = "Please Enter Reporter";
valid = false;
}

return valid;
}

关于单击“提交”后,JavaScript 验证错误消息没有消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42495425/

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