如果输入的电子邮件与显示有效电子邮件地址的模式匹配,则下面的代码将检查电子邮件的有效性。我使用了 keyup()事件,因为它在 onCheck()中包含了 onSub(),我知道它将与模式匹配后提交表单。但是我想要的是 document.otp.submit()仅在我单击按钮时才能工作,而仅在满足 onCheck()时才必须工作。
<!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>
答案 0 :(得分:0)
只需在onSub()中调用onCheck():
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var checkBox = document.getElementById("myCheck");
if(checkBox.checked)
{
alert("suscribe");
}
else
{
alert("descuscribe");
};
};
</script>
</head>
<body>
<span>Notificaciones</span>
<input type="checkbox" id="myCheck" onclick="myFunction()">
</body>
</html>
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();
}