0

Why does the following code not work?
As soon as I click on the submit button it refreshes the page.
I have just started learning JavaScript, so if you have any suggestions to improve my knowledge about JS feel free to share those also.

<html>
    <head>
        <title>Form </title>
        <script src="form.js"></script>
    </head>
    <body>
        <form id="Form" onsubmit="return handleSubmit()">
            <input id="username" type="text" name="username ">
            <input id="password" type="password" name="password">
            <input id="submit" type="submit" name="Login">
        </form>
    </body>
</html>

function handleSubmit(){
    console.log("Hi");
    var form = document.getElementById("Form");
    console.log("va="+form.childern[0].value);
    var u = form.childern[0].value;
    if (form.childern[0].length==0 && isNaN(typeOf(u))==true){
        alert("Enter Correct username");
    } else {
        console.log("username = " +u);
    }
    return false;
}
zx485
  • 28,498
  • 28
  • 50
  • 59
Shubh
  • 1
  • 2
  • 1
    Possible duplicate of [How to prevent form from being submitted?](https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted) – cabrerahector Apr 06 '18 at 18:06

2 Answers2

1

Here's a correct code buddy.Just a small change in js.

function handleSubmit(){
    console.log("Hi");
    var form = document.getElementById("Form");
    console.log("va="+form.children[0].value);
    var u = form.children[0].value;
  var a=typeof u;
    if (form.children[0].value.length!=0 &&isNaN(u))
{       
  console.log("username = " +u);
    } else {
        alert("Enter Correct username");
       
    }
    return false;
}
<html>
    <head>
        <title>Form </title>
        <script src="form.js"></script>
    </head>
    <body>
        <form id="Form" onsubmit="return handleSubmit()">
            <input id="username" type="text" name="username ">
            <input id="password" type="password" name="password">
            <input id="submit" type="submit" name="Login">
        </form>
    </body>
</html>
Rahul
  • 108
  • 1
  • 8
0
  • You mispelled the property children, instead you wrote childern.
  • In the if statement condition you are first using typeof which is gonna return probably "string", afterwards you check to see if it is a number, but typeof always will return a string containing the type of the variable, that could be "string", "number" and etc, so isNaN will always gonna be false, e finally it compares to true which is going to evaluate to false, going to the else statement.

I'm gonna add more info as I detect them! Hope this helps for the time being!