此问题已在此处找到答案:
如何重定向到其他网页((58个答案)
两天前关门了。
有人能帮我重定向到另一个页面吗(在我的情况下,重定向到“购物车页面”)。我使用preventdefault()来避免在验证之前转到另一页,但在使用preventdefault()之后,即使在验证之后,我仍然在同一页上。请帮助我:(
<script type="text/javascript">
const form = document.getElementById('form');
const email = document.getElementById('email');
const password = document.getElementById('password');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
if(emailValue === '') {
setErrorFor(email, 'This field is required');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'This field is required');
} else {
setSuccessFor(password);
}
function setErrorFor(input, message) {
const formValidate = input.parentElement;
const small = formValidate.querySelector('small');
formValidate.className = 'form-validate error';
small.innerText = message;
}
function setSuccessFor(input) {
const formValidate = input.parentElement;
formValidate.className = 'form-validate success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
}
</script>
<form id="form" action="cart.html" method="get">
<div class="form-validate">
<label class="form-label" for="email">Email</label>
<input class="form-input" id="email" type="text">
<small>Error message</small>
</div>
<div class="form-validate">
<label class="form-label" for="password">Password</label>
<input class="form-input" id="password" type="password">
<small>Error message</small>
</div>
<div class="form-validate text-center">
<button class="btn btn-outline-dark" type="submit"><i class="fa fa-sign-in-alt me-2"></i> Log in</button>
</div>
</form>
1条答案
按热度按时间eyh26e7m1#
在名为的变量中存储表单是否有效
isValid
并将其设置为false
在你的if
其中一个字段中的语句应无效。验证后,检查是否
isValid
这是真的。如果是,请随附表格form.submit()
: