简体   繁体   中英

HTML Form Onsubmit validation doesn't working for JS function

I am trying to raise an error for a form if the fields are not numeric however it isn't raising any error and directing to the page I defined as action.

I tried to raise error with a function just alerts but it again didn't raise any error and opened the other jsp.

Below is inside head tags

<script type="text/javascript">
  function validation() {
    var a = document.getElementByid("a");
    var b = document.getElementByid("b");
    var c = document.getElementByid("c");
    var d = document.getElementByid("a").value;
    var e = document.getElementByid("b").value;
    var valid = true;
    if (a.value.length <= 0 || b.value.length <= 0) {
      alert("Lutfen alani bos birakmayiniz");
      valid = false;
    } else {
      if (isNan(d)) || isNan(e)) {
      alert("Rakam girmediniz. Rakam giriniz lütfen")
      valid = false;
    } else
      return valid;
  }
  }
</script>

Following is inside body tag

<form onsubmit="return validation();" method="get" action="response.jsp">
  </br>aaa <input type="text" id="a" value="0" />
  </br>bbb <input type="text" id="b" value="0" />
  </br>ccc <input type="text" id="c" />
  <input type="submit" value="Submit" />
</form>

I am sure that it could work even if js function is in head and form is in body.

There are multiple errors in your script code, change document.getElementByid to document.getElementById change isNan to isNaN and remove extra bracket at if(isNaN(d) ) use the below one

  <script type ="text/javascript">
            function validation()
            {
                var a = document.getElementById("a");
                var b = document.getElementById("b");
                var c = document.getElementById("c");
                var d = document.getElementById("a").value;
                var e = document.getElementById("b").value;
                var valid =true;
                if (a.value.length<=0 || b.value.length<=0)
                {
                    alert("Lutfen alani bos birakmayiniz");
                    valid =false;
                }
                else 
                {
                    if (isNaN(d) || isNaN(e))
                    {
                        alert("Rakam girmediniz. Rakam giriniz lütfen")
                        valid =false;
                    }


                }
                    return valid;

            }
        </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM