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>
Related
I was trying to code a basic login web program with javascript when I discovered a problem. I can't assign value to input function using js. So now I can't use if else to create a basic login. here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<html>
<body>
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
<script>
let username = 'username';
let password = 'password';
function login() {
if (username == a88, password == a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
</script>
</div>
</body>
</html>
please help me
Seems like the input values are not being read from the page. In order to read the input values, you will first be required to grab the input DOM elements from the page.
The input fields have id attribute assigned to them which could be used to extract these elements.
<input ... id="username" ...>
<input ... id="password" ...>
You may use query selectors for that:
# Extract username input field
const usernameInputField = document.querySelector('#username')
# Extract password input field
const passwordInputField = document.querySelector('#password')
In the above snippet, document.querySelector is used to extract any DOM elements from the webpage. This function takes in the CSS selector as a parameter. Here, #username and #password are the CSS selectors for username and password fields respectively. The # sign signifies to select using the DOM element's ID.
Once we have the input fields, all we are left to do is to get the current values from these fields:
# Get current input value of username input field
const username = usernameInputField.value
# Get current input value of password input field
const password = passwordInputField.value
We use the value property of the input element to grab the current input value.
Solution:
// Grab the input fields from the page
const usernameInputField = document.querySelector('#username')
const passwordInputField = document.querySelector('#password')
function login() {
// Grab current input values
const username = usernameInputField.value
const password = passwordInputField.value
// The remaining code below stays the same
if (username === a88, password === a89) {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
In the login() function, we take the current value of the input fields and do the validation as it was handled previously. Note that, we do that inside the function itself to ensure that we have the latest value from the input fields.
The document.getElementById() method is used to select HTML elements by id. It is used as the rvalue of the value property to read the value of the HTML element.
/* The following method is used to select HTML elements based on the id attribute. */
const userNameElem = document.getElementById('username');
const passwordElem = document.getElementById('password');
const submitButton = document.getElementById("submit");
/* You can define the user name as a string as follows. */
const username = 'george';
/* You can define the user password as a string as follows. */
const password = '12345';
/* It is not recommended to assign a function to the "onclick" attribute in an HTML file. */
submitButton.addEventListener("click", function() {
if(userNameElem.value == username && passwordElem.value == password) {
alert("TRUE");
}
else {
alert("FALSE");
}
});
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47"><br><br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47"><br>
<button type="button" id="submit" class="login">Login</button>
</div>
The below code may help you. And I think Web forms — Working with user data will help you more.
function login() {
const username = document.getElementById("username").value
const password = document.getElementById("password").value
// I change "a88", "a89" to strings, not variables.
// Change back if I'm wrong.
if (username == "a88", password == "a89") {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
</div>
/* "onclick" function invoked from HTML file. */
function submit() {
/* sample user name */
const username = 'tony';
/* sample password */
const password = '1234';
const userNameElem = document.getElementById('username');
const passwordElem = document.getElementById('password');
const submitButton = document.getElementById("submit");
if(userNameElem.value == username && passwordElem.value == password) {
alert("TRUE");
}
else {
alert("FALSE");
}
};
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47"><br><br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47"><br>
<button type="button" id="submit" class="login" onClick="submit()">Login</button>
</div>
You can pass values to the functions as parameters within brackets. And also whenever you try to compare strings, use quotations to wrap your strings. In your case values of a89 and a88 should be within quotes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="index.css">
<script src="index.js"></script>
</head>
<html>
<body>
<h1>Login</h1>
<div>
<input type="text" placeholder="Input username" id="username" name="username" class="a47">
<br>
<br>
<input type="text" placeholder="Input password" id="password" name="password" class="a47">
<br>
<button type="button" onclick="login()" class="login">Login</button>
<script>
let username = 'username';
let password = 'password';
function login(username,password) {
if (username === 'a88', password === 'a89') {
alert("Thành công")
}
else {
alert("Không thành công")
}
}
</script>
</div>
</body>
</html>
<script>
function login() {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
if ((username == "a88", password == "a89")) {
alert("Thành công");
} else {
alert("không thàng công");
}
}
</script>
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>
I am trying to make a login form. for some reason i am getting an error my input is 'null' or undefined even when I fill out the form and submit
<form name ="loginform" onSubmit ={validate()} method ="post">
<p>Email</p>
<input id = "mail" type = "email" name = "usr" placeholder = "Enter Email" required></input>
<p>Password</p>
<input id ="pass" type ="password" name ="pword" placeholder = "Enter Password" required></input>
<input type = "submit" name ="" value ="Login" ></input> <br />
<a id ="demo" href ="#" style={{color:'white'}} >Forget Password?</a><br />
<a href = "#" style ={{color:'white'}}>need help?</a>
</form>
function validate(){
var un =document.getElementById("mail").value;
var pw = document.getElementById("pass").value;
var usernames = "username";
var passwords = "password" ;
if ((usernames === un) && (passwords === pw)) {
window.location = " index.js ";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
-Here is the function and I get this error: TypeError: Unable to get property 'value' of undefined or null reference. any help is apprectaed
Try the following changes:
in your var username use var usernames= "email#test.com"; as your input is an email.
While adding CSS style on each line is considered bad practice, you can do it with this syntax: style = "color:white" and add, change whatever attributes you want to change.
NOTE: White text color on white page will hide it for you.
Various html errors, I suggest use test your HTML code here every time: https://validator.w3.org/
Here is the final document I have for you:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
<!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css"> -->
<script>
function validate() {
var un = document.getElementById("mail").value;
var pw = document.getElementById("pass").value;
var usernames = "email#test.com";
var passwords = "password";
if ((usernames === un) && (passwords === pw)) {
//window.location = " index.js ";
//return false;
alert("Login was Succesful"); // GOES HERE IF LOGIN WAS SUCCESSFUL
}
else {
alert("Login was unsuccessful, please check your username and
password");
}
}
</script>
</head>
<body>
<form name="loginform" onSubmit={validate()} method="post">
<p>Email</p>
<input id="mail" type="email" name="usr" placeholder="Enter Email" required>
<p>Password</p>
<input id="pass" type="password" name="pword" placeholder="Enter Password"
required>
<input type="submit" name="Login" value="Login"><br />
<a id="demo" href="#" style="color: white">Forget Password?</a><br />
need help?
</form>
</body>
</html>
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
I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.