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>
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>
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 wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
In HTML5 in Used this code, i want user to be able to add multiple email address in input box...
<div class="modal-body row-fluid" align="left">
<span class="loader-gif" style="display:none;"><img src="<?php echo $baseURL?>/watever/img/ajax-loader-horizontal.gif"></span>
Email:
<input type="email" multiple="multiple" autofocus="" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" style="display:none;width:91%;cursor:text;" />Links:
<input type="text" readonly="readonly" style="display:none;width:91%;cursor:text;" />
<span class="message" style="display:none;"></span>
</div>
I have added Multiple property in input type="email", still i am not able to add more than one email address in my browser,
i am using, firefox latest version for testing. I just want to know, what is the way, to allow user to add multiple email addresses in that input box?
and how to later retrieve those values using Javascript.
try this, include the jquery and validate js file as per your file location
<html>
<head>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
jQuery.validator.addMethod("multiemail", function (value, element) {
if (this.optional(element)) {
return true;
}
var emails = value.split(','),
valid = true;
for (var i = 0, limit = emails.length; i < limit; i++) {
value = emails[i];
valid = valid && jQuery.validator.methods.email.call(this, value, element);
}
return valid;
}, "Please separate email addresses with a comma and do not use spaces.");
$("#emailFrm").validate({
errorElement:'div',
rules: {
emails: {
required: true,
multiemail:true
}
},
messages:
{
emails: {
required:"Please enter email address."
}
}
});
});
</script>
</head>
<body>
<form method="post" id="emailFrm">
<input type="text" name="emails" />
<input type="submit" name="submit" value="submit">
</form>
</body>
demo click here
Do not use the pattern attribute for e-mail validation. The browsers validate an e-mail address in an e-mail input field.
Himanshu97, you did not specify how you entered the e-mail addresses. Browsers expect them to be separated by comma, not just space (seems weird for me).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>e-mail addresses</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>e-mail addresses</legend>
<label>e-mail addresses
<!-- use email type to enable browser to validate and display error messages
also browsers can display an optimized "keyboard"
do no use pattern, browsers have a build in pattern -->
<input type="email" name="emailAddress" id="emailAddress" value="e#e"
placeholder="e#e, mail#example.com, mail#example.org" autofocus multiple required>
</label>
<p>is valid: input is <span id="isValid">not</span> valid</p>
<p>splitted input:</p>
<ol id="splittedInput"></ol>
<button type="submit">submit</button>
</fieldset>
</form>
<script>
const MAIL_INPUT = document.getElementById('emailAddress');
const IS_VALID = document.getElementById('isValid');
const SPLITTED_INPUT = document.getElementById('splittedInput');
MAIL_INPUT.oninput = (input) => {
IS_VALID.innerText = input.srcElement.validity.valid ? '' : 'not';
const SPLITTED = input.srcElement.value.split(',');
let addresses = [];
let list = [];
for (const SPLIT of SPLITTED)
addresses.push(SPLIT.trim());
for (const ADDRESS of addresses.sort())
list.push(newListElement(ADDRESS));
SPLITTED_INPUT.replaceChildren(...list);
}
function newListElement(content) {
let li = document.createElement('li');
li.innerText = content + ' — ' + (validEmailAddress(content) ? 'valid' : 'invalid');
return li;
}
function validEmailAddress(emailaddress) {
// this regex does not validate correctly. Try abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq#a.aa (invalid)
return /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailaddress);
}
</script>
</body>
</html>