gpt4 book ai didi

javascript - 在 JSP 中使用 javascript 的所有字段未显示验证错误

转载 作者:行者123 更新时间:2023-11-30 20:35:56 26 4
gpt4 key购买 nike

我在 JSP 页面中使用 JavaScript,如果输入字段中没有提供任何值,我会尝试在所有字段中显示错误。但出于某种原因,错误消息仅针对第一个字段(即字段标签)显示。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Test</title>
</head>
<body>
<div class="container">
<br>
<h1 class="text-success text-center">Test Test</h1>
<div class="col-lg-8 m-auto d block">

<form action="#" onsubmit="return validation()" class="bg-light">

<div class="form-group">
<label>FieldLabel:</label> <input type="text" name="fieldLabel"
class="form-control" id="fieldLabel"></input> <span
id="fieldLabelError" class="text-danger"></span>
</div>

<div class="form-group">
<label>Version:</label> <input type="text" name="version"
class="form-control" id="version"></input> <span id="versionError"
class="text-danger"></span>
</div>

<input id="submit" name="submit" type="submit" value="Submit"
onclick="validation()">

</form>
</div>
</div>

<script type="text/javascript">
function validation() {
var fieldLabel = document.getElementById("fieldLabel").value;
var version = document.getElementById("version").value;
if (fieldLabel == "") {
document.getElementById("fieldLabelError").innerHTML = "**Please enter Field label";
return false;
}
if (version == "") {
document.getElementById("versionError").innerHTML = "**Please enter version";
return false;
}

return true;
}
</script>

</body>
</html>

最佳答案

因为在 validation() 函数中,当 fieldLabel 为空时,你将返回 false,所以 version 没有机会执行,如下更改代码:

   function validation() {
var fieldLabel = document.getElementById("fieldLabel").value;
var version = document.getElementById("version").value;
var isValid = true;
if (fieldLabel == "") {
document.getElementById("fieldLabelError").innerHTML = "**Please enter Field label";
isValid = false;//use a variable to set the result
}
if (version == "") {
document.getElementById("versionError").innerHTML = "**Please enter version";
isValid = false;
}

return isValid;
}

关于javascript - 在 JSP 中使用 javascript 的所有字段未显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49838632/

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