I have written the below code to make a simple form for validation of form inputs through javascript. Here username and passwords are written in the JS code, but it still shows alert message of the else loop even if giving correct credentials on the form.
Please Help?
var user = document.getElementById('username')
var pass = document.getElementById('password')
function user1() {
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" Placeholder="enter username"><br>
<input type="password" name="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
There are a few errors here:
You need to get the values of your inputs
You want to get those values when the button is clicked. Your code is grabbing them only when the page loads. Move the variable assignment into your function
You didn't give the elements ID attributes
function user1() {
var user = document.getElementById('username').value
var pass = document.getElementById('password').value
if (user == "admin" && pass == "root") {
window.open("javascript_trial.html")
alert('correct username')
} else {
alert('incorrect username or password')
}
}
<form>
<input type="text" name="username" id="username" Placeholder="enter username"><br>
<input type="password" name="password" id="password" Placeholder="enter password"><br>
<button onclick="user1()">Submit</button>
</form>
Also note that a button's default type is submit which will submit your form and reload the page after the alert is shown when clicked, so you might want to change that to type="button" to prevent that.
Related
I have made a basic html webpage having a login screen with username and password and after validating the form it will redirect to another page.
Now I want to save the data in localstorage and show the login details within the webpages as the user to see his information.
Help me to achieve the functionality by modifying my code below:
index.html -
<form class="form">
<label>Username</label>
<div>
<input type="text" id="username" placeholder="Enter Username" autocomplete="off">
</div>
<label>Password</label>
<div>
<input type="password" id="password" placeholder="Enter Password">
</div>
Forgot Password?
<input type="submit" value="Login">
</form>
script.js -
window.addEventListener("DOMContentLoaded", () => {
document.querySelector(".form").addEventListener("submit", function(e) {
const username = this.username.value;
const password = this.password.value;
if(username.length > 4 && password.length > 4){
this.action = "landing.html";
} else {
e.preventDefault();
alert("Invalid credentials");
}
})
})
So I want to store the username and password in the localstorage and display the information in the landing page after validating the form data on login page.
Guide me how I can achieve the functionality I want to implement.
I'm designing a login form where the username and password get validated. If the user inputs are correct then I need to navigate to a different page else display an error message. The problem I'm facing is that I'm unable to navigate to another page after validation. The only way I can switch to another page is by entering the html file's name directly in the form action attribute. Here is my code:
<form id="form" action="submit.php" target="_blank" method="post" >
<div class="container">
<label for="uname"><b>Username</b></label>
<input id="usrname" type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input id="passwrd" type="password" placeholder="Enter Password" name="psw"
required>
<button type="submit" onClick="validateForm()">Login</button>
</div>
</form>
<script>
function validateForm() {
var un = document.querySelector('#usrname').value;
var pw = document.querySelector('#passwrd').value;
var username = "admin";
var password = "pass";
if ((un == username) && (pw == password)) {
alert('You are successfully logged in');
location.replace("https://google.com")
}
else {
alert("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
Try this:
In the if statement, replace this:
location.replace("https://google.com")
And try using this:
window.location.href= "https://google.com"
I know that you use php to make logins with usernames and passwords but I'm still learning HTML, is there a way to make a form with one correct username and one correct password which are hardcoded using HTML or JS?
So for example if the user enters username abcd and password pass12345, then it goes to the next screen, otherwise it says "Sorry, password is incorrect."
This is just for learning purposes, I know it's not secure at all and shouldn't be used for actual websites. Just learning. Thanks :)
The login page right now...
<form action="loggedin.html">
<label for="username">Username</label>
<input
type="text"
placeholder="Enter Username"
name="username"
required
/>
<label for="password">Password</label>
<input
type="password"
placeholder="Enter Password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
DON'T EVER USE IN PRODUCTION - LEARNING PURPOSES ONLY
As this is for learning purposes only and you understand it's not secure, I have gone ahead and written a small snippet that will check against a hard coded username and password. If entered username or password do not match it will alert the user.
I have added comments through out the code to explain what I did and what's going on.
See below
<!--
Added onsubmit attribute to form so that it will trigger the JS function (authenticate).
if the function returns false it will prevent the form from submitting
-->
<form action="loggedin.html" onsubmit="return authenticate()">
<label for="username">Username</label>
<!-- added IDs to the inputs -->
<input
id="username"
type="text"
placeholder="Enter Username"
name="username"
required
/>
<label for="password">Password</label>
<input
id="password"
type="password"
placeholder="Enter Password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
<script>
//Following function gets values of the username and password fields and checks to see if they match a hard coded username and password
function authenticate(){
var authorised;
//get input values
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
//check to see if the password and username match
if(username == "abcd" && password == "pass12345"){
authorised = true;
}else{ // username or password do not match
authorised = false;
//alert user
alert("Sorry, password is incorrect.");
}
//return result
return authorised;
}
</script>
I am validating a login form. My password field is working perfectly as I want but while validating USERNAME field I'm calling ajax for username validation i.e to check if username exists and after that if username field is empty calling a js function which shows a message but here I'm having a popup message but I wanted to display that message above the textbox. How can i do that?
Thanks in advance. :)
Add an error holder before the input box.
<span style="display:none;color:#E84344;" id='USERNAME_ERROR'> </span>
<input type="text" name="USERNAME" id="USERNAME" class="form-control input-lg" placeholder="Email or User Name" onchange="CheckLoginCustomer('loginform')"/>
Following Change you need to do in loginvalidation function
function loginvalidation(formname)
{
var form=document[formname];
var USERNAME= form.USERNAME.value;
var PASSWORD= form.PASSWORD.value;
var userNameFlag = form.userNameFlag.value;
if(USERNAME == '')
{
document.getElementById('USERNAME_ERROR').innerHTML = 'Please Enter Registered UserId';
document.getElementById('USERNAME_ERROR').style.display = 'block';
return false;
}
.....
.....
Whereever you dont want to show this error message do the following:
document.getElementById('USERNAME_ERROR').innerHTML = '';
document.getElementById('USERNAME_ERROR').style.display = 'none';
Do the same for others ..
i'm making a code for you please check below link:
https://jsfiddle.net/fatehjagdeo/9way7qc2/1/
or check my code below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form>
<input type="text" id="username"><br>
<input type="password" id="password"><br>
<input type="button" value="submit" id="submit">
</form>
<script>
$(document).on('click','#submit',function(){
$('.error').remove();
var username=$('#username').val();
var password=$('#password').val();
var err=0;
if(username==""){
$('#username').before('<p class="error">Please enter username</p>');
err=1;
}
if(password==""){
$('#password').before('<p class="error">Please enter password</p>');
err=1;
}
if(err==0){
// send your ajax here
}
});
</script>
I have a subscription form on my website that I am trying to validate. When the user clicks the button signup the function validate() is called and the fields should get validated however im not getting it to work.
Obviously there are some errors in my code. I have tried to fix it with the little knowledge I have, but can't get it to work. I would greatly appreciate it if you could point me into the right directions as to what I am doing wrong.
Code follows:
function validate()
{
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var nat = document.getElementById("nat").value;
var address = document.getElementById("address").value;
var town = document.getElementById("town").value;
var zip = document.getElementById("zip").value;
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var password2= document.getElentById("password2").value;
if (name == "" )
{
window.alert("Please Enter your Full Name")
}
checkNr= isNaN(phone)
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
if (nat == "")
{
window.alert("Please enter your nationality")
}
if (address == "")
{
window.alert("Please Enter your address")
}
if (password != password2)
{
window.alert("Your passwords did not match. Please re-enter")
}
}
</script>
HTML:
<form name="subscribe">
FULLNAME: </strong><input type="text" id="name"/><br />
PHONE NR: <input type="text" id="phone" onblur="validateForm()" /><br />
NATIONALITY:<input type="text" id="nat" /><br />
Address:<input type="text" id="address" /><br />
Town:<input type="text" id="town" /><br />
Zip Code: <input type="text" id="zip" /><br />
Username: <input type="text" id="userName" /><br />
Password:<input type="password" name="password" /><br />
Retype:<input type="password" name="password2" /><br />
<input type="button" value="submit" onclick="validate()" />
</form>
I found these mistakes in your code:
there is no validateForm() function specified in your phone input field
if you want your form to send data, set the type submit, not button on your submit button
if you want to stop the form submitting when something is not filled, hook the onsubmit event of the form:
<form onsubmit="return validate()"> ... // note the return keyword
and the script
function validate() {
...
if(somethingIsWrong) return false; // false stops submitting
else return true; // do submit
}
also note the getElentById typo mentioned by #FranciscoAfonzo
I found my mistake. It looks like you can not use the document.get with a password input field. I took out the password and it worked. It would be great if I could get some input from someone more experience as to why.
A couple of suggestions:
In JavaScript comparisions are done using === (equal to) and !== (not equal to).
If you have only the variable name in the if loop that will also suffice.
Like:
if (address)
{
window.alert("Please enter your address")
}