I've seen a couple answers on Stack but none of them detail how exactly this works. Currently I have a simple form with username and password forms which works with predefined values but not working when values are in an array. I want to use JS to validate the forms that both password and username match data points as strings within the forms. My code below has no errors to my knowledge, but my logic statements don't fire a correct entry. How can I fix this? (I included jQuery because I know a little bit in that realm and if it helps I'll take it.)
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = [["46179"], ["55678"]];
var existingPassWord = [["helloworld123"], ["helloworld456"]];
if (userNameInput == existingUserName && passWordInput == existingPassWord) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>
I just corrected your condition, please check this: (If username and password both found in existing array then it will be triggered the warning "Incorrect Username or Password")
Note: If it's not fulfill your requirement, then please let me know.
<!DOCTYPE html>
<html>
<head>
<title>Coding Project</title>
</head>
<body style="font-family:Helvetica">
<h1>
Simple Login Form:
</h1>
<form>
<input type="text" id="username" placeholder="Enter username" value=""> <br> <br>
<input type="password" id="password" placeholder="Enter password" value=""> <br> <br>
<button type="button" onClick="mySubmit()"> Submit
</button>
</form>
<script type="text/javascript">
function mySubmit() {
var userNameInput = document.getElementById("username").value;
var passWordInput = document.getElementById("password").value;
var existingUserName = ["46179", "55678"];
var existingPassWord = ["helloworld123", "helloworld456"];
if (!existingUserName.includes(userNameInput) && !existingPassWord.includes(passWordInput)) {
alert("Correct Username");
} else if (userNameInput == "" && passWordInput == "") {
alert("Empty field, please enter Username and Password or Signup");
} else {
alert("Incorrect Username or Password");
}
}
</script>
</body>
</html>
Related
My goal is to make it so that when I enter the correct word value into the text box it will return the words defined by the message variable and when the words do not match it gives the opposite message. The problem I am having is that nothing happens at all when I enter the values either correctly or incorrectly and press the button.
<html>
<head>
<meta charset="ISO-8859-1" />
<title>Login</title>
<script type="text/javascript">
function CheckCredentials() {
var username = parseFloat(document.getElementById("userbox").value);
var password = parseFloat(document.getElementById("pwdbox").value);
var message = "";
username = document.getElementById("userBox").value;
password = document.getElementById("pwdBox").value;
// insert if statement here to check user's credentials
if (username == 'student' && password == 'cs112') {
message = "hi";
} else {
message = "bye";
}
document.getElementById("outputDiv").innerHTML = message;
}
</script>
</head>
<body>
<p>Username: <input type="text" id="userBox" /></p>
<p>Password: <input type="password" id="pwdBox" /></p>
<input type="button" value="Login" onclick="CheckCredentials();" />
<div id="outputDiv"></div>
</body>
</html>
How can I make password field to check each other that the value written by user matches ?
function checkPassword(form) {
pOne = form.pOne.value;
pTwo = form.pTwo.value;
// If password not entered
if (pOne == '')
alert("Please enter Password");
// If confirm password not entered
else if (pTwo == '')
alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
// alert ("\nPassword did not match: Please try again...")
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password does not match!"
}
}
// If same return True.
else {
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password match perfectly!"
}
}
}
<form class="formtwo" onsubmit="checkPassword(this)">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You need to add the event listener to the form submit before you test
window.addEventListener("load", function() {
document.getElementById("formtwo").addEventListener("submit", function(e) {
const pOne = this.pOne.value;
const pTwo = this.pTwo.value;
const pass = document.querySelector(".pass");
let errors = [];
// If password not entered
if (pOne == '') errors.push("Please enter Password");
if (pTwo == '') errors.push("Please enter confirm password");
if (pOne != pTwo) errors.push("Password did not match: Please try again...")
if (errors.length > 0) {
e.preventDefault(); // this will stop submission
alert(errors.join("\n"))
pass.textContent = "Your password does not match!"
return;
}
pass.textContent = "Your password match perfectly!"
})
})
<form id="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You can check my solution. Hope it's easier to understand. There were some issues in your code.
If you want to prevent the form submit if the password doesn't match then you need to use event.preventDefault to prevent the default behaviour.
You can fire the submit event once and then check for your required values.
const form = document.querySelector('.formtwo');
form.addEventListener('submit', checkPassword);
function checkPassword(e) {
e.preventDefault();
let pOne = form.pOne.value;
let pTwo = form.pTwo.value;
// If password not entered
if (pOne == "") alert("Please enter Password");
// If confirm password not entered
else if (pTwo == "") alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
document.querySelector(".pass").textContent =
"Your password does not match!";
}
// If same return True.
else {
document.querySelector(".pass").textContent =
"Your password match perfectly!";
// submitting form
form.submit();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">Password matching status</p>
<button type="submit" class="submit">Submit</button>
</form>
</body>
</html>
I am trying to do a login form by using JSON, below is my code:
<html>
<head>
<title> Login Form</title>
<script>
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var Userlist = [{"username":"asdf", "password":"123"}, {"username":"zxc", "password":"123"}]
var jobj = JSON.parse(Userlist);
for (var i=0; i < jobj.length; i++) {
if ( username == jobj.username && password == jobj.password)
{
alert ("Login successfully");
}
else{
alert("Invalid username and password");
}
}
}
</script>
</head>
<body>
<div class="container">
<div class="main">
<h2>Login Form</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" placeholder="Enter username" name="username" id="username"/>
<label>Password :</label>
<input type="password" placeholder="Enter Password" name="password" id="password"/>
<input type="button" value="Login" id="submit" onclick="validate()"/>
</form>
</body>
</html>
I am unable to achieve this, when I enter with the given credentials nothing is appearing on the screen, Do I have to add some more functionality to achieve?
Working example
You don't need :
var jobj = JSON.parse(Userlist);
Just parse array like :
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var Userlist = [{"username":"asdf", "password":"123"}, {"username":"zxc", "password":"123"}];
var logged = false;
for (var i=0; i < Userlist.length; i++) {
if ( username == Userlist[i].username && password == Userlist[i].password)
logged=true;
}
if(logged)
alert ("Login successfully");
else
alert("Invalid username and password");
}
Hope this helps.
alert is not working as expected! i don't know why...
I am trying to evaluate a form on client side. I have tried getElementsById, getElementsByName.
Where am i going wrong?
I am sure the flow of control goes through validate()
an alert statement immediately inside validate method is being displayed!
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="Error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexof('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
</script>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName : <input type="text" name="uname" id="uname" value='${ param.uname}'placeholder="Enter Name" ><br/><br/>
Enter Email: <input type="email" name="email" id = "email" value='${param.email}'placeholder="Enter Email"><br/><br/>
Enter Password: <input type="password" name="pass" id = "pass" value='${param.pass}'placeholder="Enter password"><br/><br/>
Repeat Password: <input type="password" name="rpass" id = "rpass" value='${param.rpass}'placeholder="Repeat Password"/><br/>
<br/><br/>
<input type="submit"/>
</form>
<h4>${errorMsg}</h4>
</body>
</html>
Spelling of alret and indexOf !
getElementById is singular
submitOK="false" sets submitOK to true since a non-empty string is truthy. use submitOK=false
you did not return submitOK when you asked the question
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexOf('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName :
<input type="text" name="uname" id="uname" value='${ param.uname}' placeholder="Enter Name">
<br/>
<br/>Enter Email:
<input type="email" name="email" id="email" value='${param.email}' placeholder="Enter Email">
<br/>
<br/>Enter Password:
<input type="password" name="pass" id="pass" value='${param.pass}' placeholder="Enter password">
<br/>
<br/>Repeat Password:
<input type="password" name="rpass" id="rpass" value='${param.rpass}' placeholder="Repeat Password" />
<br/>
<br/>
<br/>
<input type="submit" />
</form>
First check the spelling s and correct them. Then comment all the feilds and start troubleshooting them line by line. You will win. Regards !
I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd