Debarghya Chakraborty
Debarghya Chakraborty

Reputation: 73

Why this form validation code not working?

After entering the correct username and password I'm not getting forwarded to 'another.html'. How to resolve this ? Any suggestions ? [Extra text to reach word limit cause otherwise the question won't get post]

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" language="javascript">
        document.writeln("<h1 id= 'heading' style='color:blue;background-color:yellow'><center>Welcome to my website</center></h1>");
        document.writeln('<br/><br/><br/>');
        document.writeln();
        function validate()
        {
            var username = document.getElementById("username");
            var password = document.getElementById("password");

            if(username.value == "username" && password.value == "password")
            {
                
                return true;
            }
            else
            {
                alert("Please enter all fields");
                return false;
            }
        }
    </script>
        
    
</head>
<body>
    <form onsubmit="return validate()" action="another.html">
        <input id="username" type="text" name="username" placeholder="username" /><br/><br/>
        <input id="password" type="password"name="password" placeholder="password" /><br/><br/>
        <button type="button">SUBMIT</button>
    </form>
</body>
</html>

Upvotes: 0

Views: 71

Answers (3)

Oussama Zeaiter
Oussama Zeaiter

Reputation: 127

Your function is not getting called because your button type is set to button.

Change:

<button type="button">SUBMIT</button>

To:

<button type="submit">SUBMIT</button>

Upvotes: 0

Harshit
Harshit

Reputation: 128

Actually you are calling your validate function on "onsubmit" so you have to have button of type submit

<button type="submit">SUBMIT</button>

Without button of type submit your function won't be called.

Upvotes: 0

Robert Cooper
Robert Cooper

Reputation: 2240

You need to have a button type of submit in order to be able to submit your form by clicking the button.

<button type="submit">SUBMIT</button>

By default, button's have a type of submit, so you can even get away with leaving this attribute off your button.

<button>SUBMIT</button>

Upvotes: 3

Related Questions