简体   繁体   中英

Javascript Basic Login Function

can any1 explain it to me why this isnt working? Here's the script

 <script type= "text/javascript"> function login() { var user = document.getElementById("username").value; var pass = document.getElementById("password").value; if(user == "lab18" && pass == "lab18") { alert("Logged In"); locate="new11.html" return false; } else { alert("wrong user/pass"); return false; } } </script> 

And here's the form:

 <form name="Form" onsubmit="login()"> <input type="submit" value="Log In" style = font-family:'Comic Sans Ms'> 

It is important to note that when you submit the form, it'll redirect the user to the the page specified by the action attribute. That being said, your form lacks an action or method . You can read more about how to construct a proper form here .

Not handling your JavaScript inline with your HTML is a good habit to get into, so I suggest you add an event listener to your form. Consider the following revisions:

I removed the onsubmit attribute from your form and gave it a unique ID:

<form id="myForm" name="Form">

Now let's add an event handler for when your form submits (since you don't seem to want the form to actually submit , we can prevent that default behavior from happening):

document.querySelector("#myForm").addEventListener("submit", function(e){
    // Prevent the form from submitting
    e.preventDefault();
    // login() will be called when the form is submitted
    login();
});

Working Fiddle

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