javascript - Stop Auto Submission of Form on KEYUP and make onSub() work when only onCheck() is Satisfied
问题描述
Here the below code will check for validation of email if the entered email is matched with the pattern it will show valid email address. I used keyup() event i know it will submit the form after matching with the pattern because i included onSub() in onCheck(). But what i want is document.otp.submit() has to work only when i click on the button but it has to work only when onCheck() is satisfied.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<script type="text/javascript">
function onCheck() {
var pattern = /^\S+@\S+\.\S+$/;
var a=document.getElementById('email').value;
if (pattern.test(a)) {
document.getElementById('messages').style.color = 'green';
document.getElementById('messages').innerHTML = "valid email id";
onSub();
} else {
document.getElementById('messages').style.color = 'red';
document.getElementById('messages').innerHTML = "invalid email id";
}
}
function onSub(){
document.otp.submit();
}
</script>
<body style="align:center">
<form name="otp" action="Otp" method="get">
<label for="Email"><b>Email</b></label>
<input type="email" id="email" name="email" onkeyup="onCheck()" placeholder="Enter Email.." ><span id='messages'></span><br><br>
<button type='button' onclick="onSub()">Send OTP</button>
</form>
</body>
</html>
解决方案
Just call onCheck() within onSub():
function onCheck() {
var pattern = /^\S+@\S+\.\S+$/;
var a = document.getElementById('email').value;
if (pattern.test(a)) {
document.getElementById('messages').style.color = 'green';
document.getElementById('messages').innerHTML = "valid email id";
return true;
} else {
document.getElementById('messages').style.color = 'red';
document.getElementById('messages').innerHTML = "invalid email id";
return false;
}
}
function onSub() {
if (onCheck())
document.otp.submit();
}
<form name="otp" action="Otp" method="get">
<label for="Email"><b>Email</b></label>
<input type="email" id="email" name="email" onkeyup="onCheck()" placeholder="Enter Email.."><span id='messages'></span><br><br>
<button type='button' onclick="onSub()">Send OTP</button>
</form>
推荐阅读
- dialogflow-es - 有没有办法在 Dialogflow 中检查一个问题是否以前被问过,如果是,就不要再问了?
- java - 数据为空或空白时如何避免更新子表?
- powershell - 将数组数据重新排列到表中
- c# - 具有代理用户的 Oracle.ManagedDataAccess.Client 出现错误 ORA-01017:用户名/密码无效;登录被拒绝
- node.js - 尝试使用 Nodejs 中的 cloudmersive API 将办公文档转换为 PDF(NOOB)
- android - 无法编译 Android 应用程序
- symfony - Sylius:重定向时缺少路由参数 (SyliusResourceBundle)
- r - R:创建一个新的data.frame,由来自另一个data.frame的不同长度的子集的平均值组成
- php - Laravel 上的 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 错误
- python - selenium.common.exceptions.ElementClickInterceptedException:消息:元素点击被拦截