我有一个使用Bootstrap 4设计的简单html页面。有两个小表格,一个放在另一个表格下面。我已经在两个表单中启用了引导表单验证。我希望页面首次加载时仅第一种形式可见。第二个应该保持隐藏。用户单击第一个表单上的“提交”按钮后,第一个表单应被隐藏,而第二个表单应被显示。以下是表单的代码:
<main role="main" class="container">
<div class="container" id="emailDiv">
<form action="#" class="needs-validation" novalidate>
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" class="form-control" id="email" placeholder="Enter registered email" name="email" required>
<div class="valid-feedback">Entry validated!</div>
<div class="invalid-feedback">Please fill out this mandatory field.</div>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="checkterms" required> Terms & Conditions
<div class="valid-feedback">You have accepted the terms & conditions.</div>
<div class="invalid-feedback">Acceptance of the terms & conditions is mandatory.</div>
</label>
</div>
<button type="submit" class="btn btn-primary" id="SendOTPButton" onclick="hideEmailForm()">Send OTP</button>
</form>
</div>
<div class="container" id="otpDiv">
<form action="#" class="needs-validation" novalidate>
<div class="form-group mt-3">
<label for="otp">Enter OTP:</label>
<input type="text" class="form-control" id="otp" placeholder="Enter the OTP which has been sent to your registered email address." name="otp">
<div class="valid-feedback">OTP entered.</div>
<div class="invalid-feedback">Please enter the mandatory OTP.</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<br>
<script>
// Disable form submissions if there are invalid fields.
(function() {
'use strict';
window.addEventListener('load', function() {
// Get the forms we want to add validation styles to.
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script>
document.getElementById("emailDiv").style.display="block";
document.getElementById("otpDiv").style.display="none";
</script>
<script>
function hideEmailForm() {
document.getElementById("emailDiv").style.display="none";
document.getElementById("otpDiv").style.display="block";
}
</script>
</main>
我尝试使用<script>
标签中包含的Javascript函数隐藏第一个表单。隐藏和显示功能可以按预期工作,但是onclick事件会覆盖Bootstrap 4的表单验证。第一个表单在没有表单验证的情况下被隐藏,第二个表单被显示。我希望先验证第一个表单,然后将其隐藏。如果验证失败,则第一个表格不应被隐藏。
有什么建议吗?