Why the paragraphs arent showing up when inputs are empty - javascript

im pretty new to coding and i wanted to try to make a register form and use javascript to check if any of the forms are empty. I tried to make it using DOM but it seems that its not working. If anyone can help me i will be really thankful.
js code:
let btnCheck = document.querySelector('#claim');
let input = document.querySelectorAll('input');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
function checkForBlank(){
if (document.querySelector('#fname').value == ""){
fname.innerHTML = 'First Name cannot be empty'
}
if (document.querySelector('#lname').value == ""){
lname.innerHTML = 'Last Name cannot be empty'
}
if (document.querySelector('#email').value == ""){
email.innerHTML = "Looks like this is not an email"
}
if (document.querySelector('#password').value ==""){
password.innerHTML = 'Password cannot be empty'
}
}
btnCheck.addEventListener('click', checkForBlank());
html code:
<form>
<input type='text' placeholder="First Name">
<p id='fname'></p>
<input type='text' placeholder="Last Name">
<p id='lname'></p>
<input type='text' placeholder="Email Address">
<p id='email'></p>
<input type='password' placeholder="Password">
<p id='password'></p>
</form>

Your code does not check to see if the form input field is empty currently. You would want to get reference to the input and check to see if that is empty.
<form>
<input id="fname-input" type="text" placeholder="First Name" />
<p id="fname"></p>
<input id="lname-input" type="text" placeholder="Last Name" />
<p id="lname"></p>
<input id="email-input" type="text" placeholder="Email Address" />
<p id="email"></p>
<input id="password-input" type="password" placeholder="Password" />
<p id="password"></p>
</form>
const btnCheck = document.querySelector('#claim');
const fname = document.querySelector('#fname');
const fnameInput = document.querySelector('#fname-input');
const lname = document.querySelector('#lname');
const lnameInput = document.querySelector('#lname-input');
const email = document.querySelector('#email');
const emailInput = document.querySelector('#email-input');
const password = document.querySelector('#password');
const passwordInput = document.querySelector('#password-input');
function checkForBlank() {
if (fnameInput.value == "") {
fname.innerHTML = "First Name cannot be empty";
}
if (lnameInput.value == "") {
lname.innerHTML = "Last Name cannot be empty";
}
if (emailInput.value == "") {
email.innerHTML = "Looks like this is not an email";
}
if (passwordInput.value == "") {
password.innerHTML = "Password cannot be empty";
}
}
btnCheck.addEventListener('click', checkForBlank);
Additionally, you need to pass a function reference to addEventListener instead of invoking the function.
btnCheck.addEventListener('click', checkForBlank()); // WRONG
btnCheck.addEventListener('click', checkForBlank); //RIGHT
Note: I would recommend to rather (or additionally) use the required property of html elements https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required

There are multiple things that you need to refactor
It would be better to create a new HTML element for errors with different classes.
As you are wrapping the inputs in the form element, So you need to preventDefault.
For clickListener you need to pass the function reference only, no need to execute the function
// INPUTS
let btnCheck = document.querySelector('#claim');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
// INPUT ERRORS
let fnameError = document.querySelector('#fname-error');
let lnameError = document.querySelector('#lname-error');
let emailError = document.querySelector('#email-error');
let passwordError = document.querySelector('#password-error');
function checkForBlank(e) {
e.preventDefault();
console.log(fname.value);
if (fname.value === "") {
fnameError.textContent = 'First Name cannot be empty'
} else {
fnameError.textContent = ''
}
if (lname.value === "") {
lnameError.textContent = 'Last Name cannot be empty'
} else {
lnameError.textContent = ''
}
if (email.value === "") {
emailError.textContent = "Looks like this is not an email"
} else {
emailError.textContent = ''
}
if (password.value === "") {
passwordError.textContent = 'Password cannot be empty'
} else {
passwordError.textContent = ''
}
}
btnCheck.addEventListener('click', checkForBlank);
p.error{
color: red;
font-size: 12px;
padding: 0;
margin: 4px 0 8px 0;
}
<form>
<input type='text' placeholder="First Name" id='fname'>
<p class="error" id="fname-error"></p>
<input type='text' placeholder="Last Name" id='lname'>
<p class="error" id="lname-error"></p>
<input type='text' placeholder="Email Address" id='email'>
<p></p>
<p class="error" id="email-error"></p>
<input type='password' placeholder="Password" id='password'>
<p></p>
<p class="error" id="password-error"></p>
<button id="claim"> check </button>
</form>

Related

Form Validation: messages not displaying when all input fields are left empty

So I am practicing Javascript and right now I am trying to implement form validation.
One of the issues I am having is that when I click on the button when all of the input fields are empty, the first one (Full Name) only highlights and displays a message (Please checkout snippet). I was wondering is that how it works - can only one message be displayed at a time or is there a way to get all of the input fields to change color and display messages for each empty field?
function validateForm(e) {
const eName = document.getElementById("FullName");
const eMail = document.getElementById("Email");
const ePhone = document.getElementById("PhoneNumber");
const ePass = document.getElementById("Password");
const eCnfmPass = document.getElementById("ConfirmPassword");
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
const fullNameText = "Oops, please fill out your name";
const emailText = "Please enter a valid email";
const phoneText = "Please enter a valid phone number";
const passText = "Please enter a valid password";
const confirmText = "Please confirm your password";
//Name input validation - If input is left empty
if (eName.value === "") {
e.preventDefault();
document.getElementById("FullName").style.borderColor = "red";
document.getElementById("FullNameLabel").innerHTML = fullNameText;
document.getElementById("FullNameLabel").style.color = "red";
return false;
}
//Email input validation - If input is left empty
if (eMail.value === "") {
e.preventDefault();
document.getElementById("Email").style.borderColor = "red";
document.getElementById("EmailLabel").innerHTML = emailText;
document.getElementById("EmailLabel").style.color = "red";
return false;
}
//Phone number input validation - If input is left empty
if (ePhone.value === "") {
e.preventDefault();
document.getElementById("PhoneNumber").style.borderColor = "red";
document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Phone number input validation - checks to see if there is a missing number or character that is not a number
if (ePhone.value.match(phoneno)) {
return true;
} else {
alert("Please check your phone number and enter it again")
// document.getElementById("PhoneNumber").style.borderColor = "red";
// document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
// document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Password input validation - If input is left empty
if (ePass.value === "") {
e.preventDefault();
document.getElementById("Password").style.borderColor = "red";
document.getElementById("PasswordLabel").innerHTML = passText;
document.getElementById("PasswordLabel").style.color = "red";
return false;
}
//Confirm password input validation - If input is left empty
if (eCnfmPass.value === "") {
e.preventDefault();
document.getElementById("ConfirmPassword").style.borderColor = "red";
document.getElementById("ConfirmPswdLabel").innerHTML = confirmText;
document.getElementById("ConfirmPswdLabel").style.color = "red";
}
}
//Checks to make sure that both password and confirm passwords match
var passConfirm = function() {
if (document.getElementById("Password").value ==
document.getElementById("ConfirmPassword").value) {
document.getElementById("Message").style.color = "green";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords match!"
} else {
document.getElementById("Message").style.color = "red";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords do NOT match!"
}
}
<div class="container">
<form class="form" onsubmit="validateForm(event)">
<div>
<label id="FullNameLabel">Full Name</label></br>
<input type="text" placeholder="John Doe" id="FullName" />
</div>
<div>
<label id="EmailLabel">Email</label></br>
<input type="text" placeholder="johndoe#email.com" id="Email" />
</div>
<div>
<label id="PhoneNumberLabel">Phone Number</label></br>
<input type="text" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div>
<label id="PasswordLabel">Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onkeyup='passConfirm();' />
</div>
<div>
<label id="ConfirmPswdLabel">Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onkeyup='passConfirm();' />
</div>
<span id="Message"></span>
<button type="submit" value="submit">Sign Me Up!</button>
</form>
</div>
You have too much javascript code, you can simplify that, alot.
to check if any of the inputs are empty, you can first store all the inputs in a variable like that:
let inputs = document.querySelectorAll('.form input') //This will make a Nodelist array of all the inputs inside the form.
let labels = document.querySelectorAll('.form label') //This will make a Nodelist array of the label tags inside the form
after that you can loop through the inputs array to find if any of the inputs are empty:
for (let i = 0; i < inputs.length; i++) {
if (inputs.value.length == 0) {
inputs[i].style.borderColor = 'red'
label[i].textContent = 'Please fill in this input'
}
}
Require your inputs. Why go through all that trouble making sure they're filled out?
<input required>

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

Script not targeting certain elements by ID, works fine on others

If one of the identified DOM elements is empty, change the background color to red, if not, change to transparent. Why does this not work on the phone or position fields?
I have another script targeting elements like document.forms["pledge"]["position"] which also works on all other fields but phone and position. What am I missing?
function checkFilled() {
var fname = document.getElementById("fname"),
lname = document.getElementById("lname"),
email = document.getElementById("email"),
country = document.getElementById("country"),
zip = document.getElementById("zip"),
position = document.getElementById("position"),
phone = document.getElementById("phone");
;
if (fname.value != "") {
fname.style.backgroundColor = "transparent";
} else {
fname.style.backgroundColor = "red";
}
if (lname.value != "") {
lname.style.backgroundColor = "transparent";
} else {
lname.style.backgroundColor = "red";
}
if (email.value != "") {
email.style.backgroundColor = "transparent";
} else {
email.style.backgroundColor = "red";
}
if (country.value != "") {
country.style.backgroundColor = "transparent";
} else {
country.style.backgroundColor = "red";
}
if (zip != undefined && zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
if (position.value != "") {
position.style.backgroundColor = "transparent";
} else {
position.style.backgroundColor = "red";
}
if (phone.value != "") {
phone.style.backgroundColor = "transparent";
} else {
phone.style.backgroundColor = "red";
}
}
HTML
<form name="pledge" id="form">
<input class="input" type="text" id="fname" name="first_name" placeholder="First Name" onchange="checkFilled()">
<input class="input" type="text" id="lname" name="last_name" placeholder="Last Name" onchange="checkFilled()">
<input class="input" type="text" id="position" name="user_position" placeholder="Position in Government" onchange="checkFilled()">
<input class="input" type="text" id="country" name="user_country" placeholder="Country" onchange="checkFilled()">
<input class="input" type="email" id="email" name="user_email" placeholder="Official Government Email" onchange="checkFilled()">
<input class="input" type="number" id="phone" name="user_phone" placeholder="Office Phone Number" onchange="checkFilled()">
<input class="input full-width" type="submit" value="Take The Pledge!">
</form>
https://codepen.io/froggomad/pen/maRJxr
The script was failing because it was trying to handle the zip element which doesn't exist on this form. I mistakenly tried to handle that condition by checking to see if it existed and contained a value and then changing its background color if both conditions weren't true (OOPS)
Working Code
if (zip != undefined) {
if (zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
}
Your form does not have an element with the zip id and is therefore throwing errors trying to modify the zip style property in the else statement of your zip check since it is null. Since that error causes the function to fail, the position and phone based if statements don't execute.
If you remove the if/else block checking the zip variable, both of those fields work again.

Disable Button for form

I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>

Javascript not working in html file

I have written code for a basic registration page to run on my webserver but javascript doesn't seem to be working in the html file. I do a form post with a javascript function to find errors but it seems to be completely ignoring the javascript code when I test it. Is there a problem with my javascript code or in the html code? My code is shown below.
<script type="text/javascript" language="Javascript">
function checkPasswordMatch(){
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if(password != password2){
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";}
else{
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";}
}
// $(document).ready(function(){
// $("#pass2").keyup(checkPasswordMatch);
// })
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if(user=""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if(pass1=""){
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if(pass2=""){
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if(email=""){
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
</head>
<body>
<div id="link">
Home
<a align="right" href="signin">Sign-in</a>
</div>
<div id="header">
<center><h1><i>IMGCAPTURE</i></h1></center>
</div>
<div id="create">
<center><h2>Create Your Account</h2></center>
<form name="form1" action="account" onsubmit="return Error()" method="POST">
<div id="username"><center><h3>Enter Username: <input type="text" name="username" id="user" cols="15" rows="1"></input></h3></center></div>
<div id="usernameerror"></div>
<div id="password"><center><h3>Enter Password: <input type="password" name="password1" id="pass1" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror1"></div>
<div id="confirmpassword"><center><h3>Re-Enter Password: <input type="password" name="password2" id="pass2" onChange="checkPasswordMatch()" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror2"></div>
<div class="registrationFormAlert" id="divcheckpasswordmatch"></div>
<center><h3>Enter Email: <input type="email" name="useremail" id="email" cols="15" rows="1">
</input></h3></center>
<div id="emailerror"></div>
<center><input type="submit" value="Create Account" onclick="Error()"></input></center>
</form>
</div>
</body>
</html>
It may be that you are not calling the functions you are creating. So since you are not calling those functions with arguments, nothing inside them is going to happen. Let me know if this fixes it.
Also, stylistically you would want the Javascript code at the end of the HTML file.
Instead of binding your input name="password2" to the function by the onChange-tag, try binding it like this:
$(document).on('change', 'input[name="checkPasswordMatch"]', checkPasswordMatch);
function checkPasswordMatch() {
...
}
And in your HTML, remove the onChange tag:
<div id="confirmpassword">
<center>
<h3>
Re-Enter Password: <input type="password" name="password2" id="pass2" cols="15" rows="1"></input>
</h3>
</center></div>
It seems you've forgotten to include jQuery. If you use pure JS, it works :
<script type="text/javascript">
function checkPasswordMatch() {
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if (password != password2) {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";
} else {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("pass2").addEventListener('keyup', checkPasswordMatch);
});
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if (user = "") {
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if (pass1 = "") {
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if (pass2 = "") {
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if (email = "") {
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
You probably want to use == or === in your if statements. You're assigning user, etc. to an empty string in your if conditionals.
if(user == ""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}

Categories

Resources