首页 > 解决方案 > 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>

标签: javascripthtmlvalidation

解决方案


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>


推荐阅读