Shubh
Shubh

Reputation: 1

Automation Submitting the form

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;
}

Upvotes: 0

Views: 35

Answers (2)

Rahul
Rahul

Reputation: 118

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>

Upvotes: 1

Gustavo H. Ribeiro
Gustavo H. Ribeiro

Reputation: 15

  • 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!

Upvotes: 0

Related Questions