开发者

alert message not closing when validation fails

Not getting what am I doing wron here. The alert essage never close when the validation fails

<!DOCTYPE html>
<html>
<head>
<script>

function checkNumber(numField) {
    var num = numField.value;
    if(num < 1) {
        getMessage();
        numField.focus();
   开发者_开发百科 return false;
    }
    return true;
}

function getMessage(numField) {
    alert("Not a valid number. Accepts only postive numbers between ");
}

function setTabOut() {
  document.forms[0].elements['taboutFlag'].value = "true";
}

 
</script>
</head>
<body>

<form>
    <p id="demo"></p>

    <input type="text" name="username" onblur="setTabOut();return checkNumber(this);" />

    <INPUT type="hidden" name="taboutFlag" />
</form>
</body>
</html>


You are experiencing this problem because immediately after calling getMessage and showing the alert, you focus right back onto the input. When you close the alert, you are losing focus on the input again, so the blur event is fired, hence the infinite loop.

To solve this, don't focus on the input after calling getMessage.

<!DOCTYPE html>
<html>

<head>
  <script>
    function checkNumber(numField) {
      var num = numField.value;
      if (num < 1) {
        getMessage();
        return false;
      }
      return true;
    }

    let shownAlert = false;

    function getMessage(numField) {
        alert("Not a valid number. Accepts only postive numbers between ");
    }

    function setTabOut() {
      document.forms[0].elements['taboutFlag'].value = "true";
    }
  </script>
</head>

<body>

  <form>
    <p id="demo"></p>

    <input type="text" name="username" onblur="setTabOut();return checkNumber(this);" />

    <INPUT type="hidden" name="taboutFlag" />
  </form>
</body>

</html>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜