Input field value 'undefined' even with value in it - javascript

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>

Related

how to assign value to input function using javascript

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>

Trying to get a nested if statement to work

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>

prevent form from submitting not working, JavaScript

Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.

Using JavaScript to validate form both onblur and when pressing submit

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.

How to add multiple Email addresses in text input HTML

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>

Categories

Resources