I hope I don't bother you with a question :) .
I have little knowledge about writing code, so I encountered an error there are two inputs I added an eye icon with bootstrap when clicked, the password appears the first input works, but the second input does not show the password What do you think is the problem.
sorry about my bad English.
<form method="post" id="your_form_id" enctype="index.php">
<div class="input-container">
<input type="password" name="password" placeholder="Password" required="on"><br><br>
<i class="material-icons visibility">visibility_off</i>
</div>
<script>
const visibilityToggle = document.querySelector('.visibility');
const input = document.querySelector('.input-container input');
var password = true;
visibilityToggle.addEventListener('click', function() {
if (password) {
input.setAttribute('type', 'text');
visibilityToggle.innerHTML = 'visibility';
} else {
input.setAttribute('type', 'password');
visibilityToggle.innerHTML = 'visibility_off';
}
password = !password;
});
</script>
<input type="email" name="mail" id="mail" placeholder="Mail Address" required="on"><br><br>
<div class="input-container">
<input type="password" name="mailspword" placeholder="Mail Password" required="on"><br><br>
<i class="material-icons visibility">visibility_off</i>
</div>
<script>
const visibilityToggle = document.querySelector('.visibility');
const input = document.querySelector('.input-container input');
var password = true;
visibilityToggle.addEventListener('click', function() {
if (password) {
input.setAttribute('type', 'text');
visibilityToggle.innerHTML = 'visibility';
} else {
input.setAttribute('type', 'password');
visibilityToggle.innerHTML = 'visibility_off';
}
password = !password;
});
</script>
document.querySelector is going to return the first element in your page. So, your logic works fine with the first input but not in the second input as document.querySelector is still going to return the first element.
You can use document.querySelectorAll and then use indexing to access you input as below-
const visibilityToggle1 = document.querySelectorAll('.visibility')[0];
const input1 = document.querySelectorAll('.input-container input')[0];
var password1 = true;
visibilityToggle1.addEventListener('click', function() {
if (password1) {
input1.setAttribute('type', 'text');
visibilityToggle1.innerHTML = 'visibility';
} else {
input1.setAttribute('type', 'password');
visibilityToggle1.innerHTML = 'visibility_off';
}
password1 = !password1;
});
const visibilityToggle2 = document.querySelectorAll('.visibility')[1];
const input2 = document.querySelectorAll('.input-container input')[1];
var password2 = true;
visibilityToggle2.addEventListener('click', function() {
if (password2) {
input2.setAttribute('type', 'text');
visibilityToggle2.innerHTML = 'visibility';
} else {
input2.setAttribute('type', 'password');
visibilityToggle2.innerHTML = 'visibility_off';
}
password2 = !password2;
});
<form method="post" id="your_form_id" enctype="index.php">
<div class="input-container">
<input type="password" name="password" placeholder="Password" required="on"><br><br>
<i class="material-icons visibility">visibility_off</i>
</div>
<input type="email" name="mail" id="mail" placeholder="Mail Address" required="on"><br><br>
<div class="input-container">
<input type="password" name="mailspword" placeholder="Mail Password" required="on"><br><br>
<i class="material-icons visibility">visibility_off</i>
</div>
</form>
I have edited your code because of multiple variables with same name. I have appended 1 to the variables for first input and 2 to variables for second input.
As mentioned in one of the comments, I have duplicated the event listeners here for both inputs just for demonstration purpose, but you can attach the same event listener to both inputs with looping and providing a custom argument to the event listener.
Related
Please tell me how to hide the password confirmation field. I can hide the password field, but the second field does not work, does not respond
Here is my code with input
<div class="mb-3">
<label class="form-label">New password</label>
<div class="input-group input-group-flat">
<input type="password" name="password" id="password" class="form-control">
<span class="input-group-text">
<span toggle="#password" class="ti ti-eye toggle-password"></span>
</span>
</div>
</div>
<div class="mb-3">
<label class="form-label">Confirm password</label>
<div class="input-group input-group-flat">
<input type="password" name="confirm_password" id="confirm_password" class="form-control">
<span class="input-group-text">
<span toggle="#password" class="ti ti-eye toggle-password2"></span>
</div>
</div>
my js
$(".toggle-password").click(function() {
$(this).toggleClass("ti-eye-off");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
$(".toggle-password2").click(function() {
$(this).toggleClass("ti-eye-off");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
I tried changing the variables by duplicating the code, but it still doesn't work. Changing the icon eye on the field remains hidden
You are trying to change attr to input, but this variable is the span. So you need to find input by id and it works.
This will be
$(".toggle-password").click(function() {
$(this).toggleClass("ti-eye-off");
// var input = $($(this).attr("toggle")); WRONG
var input = $("#password");
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
In addition, if you want to hide/show two inputs, find by classname instead of id.
I made you a basic snippet to see it in live.
$(".toggle__password").click(function() {
$(this).toggleClass("password--hidden");
const input = $(".password");
if (input.attr("type") === "password") {
input.attr("type","text");
} else {
input.attr("type", "password");
}
});
.toggle__password {
background:red
}
.password--hidden {
background:green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="password" value="hello" class="password"/>
<input type="password" value="bye" class="password" />
<span class="toggle__password password--hidden"> Hidden </span>
</div>
I have a task:
Write a JS function that validates the content of the form - the form should have at least one mandatory numeric field and one field that simply cannot be empty. If the validation is not passed through the field, display the appropriate information to inform the user. If validation fails, the function should return false, otherwise true
So, I'm trying to return a boolean value if the from fails validation and subsequently hide the forms. I've put the boolean value into the error and success functions but it doesn't seem to work. I've tried to make the check inputs function return the boolean value but it didn't work also.
I'm just trying to learn so any help regarding the best approach to this problem logically would be appreciated. I also understand that there might have been simple syntax issues, but this is also something I'm trying to get better at right now.
const form = document.getElementById('form');
const username = document.getElementById('username');
const num = document.getElementById('num');
const phone = document.getElementById('phone');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
let isValid;
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
if (isValid = true){
form.remove;
}
});
function checkInputs() {
const usernameValue = username.value.trim();
const numValue = num.value.trim();
const phoneValue = phone.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if(numValue === ''){
setErrorFor(num, 'You must have a favorite number');
}else if(isNaN(numValue)){
setErrorFor(num, 'Not a number');
}else{
setSuccessFor(num);
}
if(phoneValue === '+48' || phoneValue === ''){
setErrorFor(phone, 'Phone cannot be blank');
}else{
setSuccessFor(phone);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
}else if (passwordValue.length < 8){
setErrorFor(password, 'Password cannot be less than 8 characters');
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password cannot be blank');
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
isValid = false;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
isValid = true;
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function test(){
if (isValid = true){
console.log('hi')
} else{
console.log('HEXYU')
}
}
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Your username" id="username" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="num">Your favorite number</label>
<input type="number" placeholder="Your favorite number" id="num"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="phone">Phone number</label>
<input type="tel" placeholder="Your phone numbe" id="phone" value="+48"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="email" placeholder="email#youremail.com" id="email" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" placeholder="Password" id="password"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="passsword2">Password check</label>
<input type="password" placeholder="Repeat your password" id="password2"/>
<small>Error message</small>
</div>
<button class="form-button" >Submit</button>
</form>
</div>
Two errors in your code:
Use remove() instead of remove
Use == / === instead of =
Also, you could use required to let user unable to submit.
num input type will only accept number input and email type input will check if there is # in the input. This will save a lot of if unnecessary if statement.
const form = document.getElementById('form');
const username = document.getElementById('username');
const num = document.getElementById('num');
const phone = document.getElementById('phone');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
let isValid;
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
if (isValid = true){
form.remove();
}
});
function checkInputs() {
const phoneValue = phone.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
setSuccessFor(username);
setSuccessFor(num);
setSuccessFor(email);
}
if(phoneValue === '+48' ){
setErrorFor(phone, 'Phone cannot be blank');
}else{
setSuccessFor(phone);
}
if (passwordValue.length < 8){
setErrorFor(password, 'Password cannot be less than 8 characters');
} else {
setSuccessFor(password);
}
if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
isValid = false;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
isValid = true;
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function test(){
if (isValid == true){
console.log('hi')
} else{
console.log('HEXYU')
}
}
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Your username" id="username" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="num">Your favorite number</label>
<input type="number" placeholder="Your favorite number" id="num" required />
<small>Error message</small>
</div>
<div class="form-control">
<label for="phone">Phone number</label>
<input type="tel" required placeholder="Your phone numbe" id="phone" value="+48"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="email" required placeholder="email#youremail.com" id="email" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" required placeholder="Password" id="password"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="passsword2">Password check</label>
<input type="password" required typeplaceholder="Repeat your password" id="password2"/>
<small>Error message</small>
</div>
<button class="form-button" >Submit</button>
</form>
</div>
How to disable submit button until the user enters all fields and also how to use event listener on submit form.
<form action='index.html' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(username,password,email)
};
Jsfiddle link
Set up a validation object with booleans to record if all your values have met validation.
Then I'd loop through all your inputs and add an event listener to each of them. In this example I've checked to see if each has at least one character in them, but you might want to expand on this.
Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.
let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');
let inputValidator = {
"username": false,
"email": false,
"password": false
}
inputs.forEach((input) => {
input.addEventListener('input', () => {
let name = event.target.getAttribute('name');
if (event.target.value.length > 0) {
inputValidator[name] = true;
} else {
inputValidator[name] = false;
};
let allTrue = Object.keys(inputValidator).every((item) => {
return inputValidator[item] === true
});
if (allTrue) {
buttonSend.disabled = false;
} else {
buttonSend.disabled = true;
}
})
})
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
This is probably not what you are looking for but you can achieve almost the same effect by simply using the required attribute in your input fields:
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username" required>
<input type="email" name="email" id="email" placeholder="email" required>
<input type="password" name="password" id="password" placeholder="password" required>
<button type="submit" name="submit" id='button-send' >SUBMIT</button>
</form>
Using the onBlur event will ensure the user has visited each field. You may also want to check the field contains a value, for that you can add the HTML required attribute.
var isDirty = {
username: false,
password: false,
email: false
}
const init = function() {
let incompleteItems = getIncompleteItems();
if(incompleteItems.length > 0) {
alert(`${incompleteItems} requires a value.`);
return;
}
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(`values: ${username}, ${email}, ${password}`);
};
const onChange = function(e) {
isDirty[e.id] = true;
}
const getIncompleteItems = function() {
let incomplete = "";
for (const [key, value] of Object.entries(isDirty)) {
if(value === false) {
if(incomplete.length > 0) {
incomplete += `, ${key}`;
}
else {
incomplete = key;
}
}
}
return incomplete;
}
<form method='GET' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username" onBlur="onChange(this)">
<input type="email" name="email" id="email" placeholder="email" onBlur="onChange(this)">
<input type="password" name="password" id="password" placeholder="password" onBlur="onChange(this)">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
Create a validation function which will check all the validations and sets the disabled property of the button if validation fails and vice versa. Call the validation function on every change of all the fields.
You can use oninput event
<input type="text" oninput="validate()">
This is a two-part question.
Part 1. The passConfirm function that I currently have is there to make sure that the password and confirming password values match. Right now, when I type in my password the button disappears. The purpose of this function is to display a message while the user is creating a password and confirming it, that the password does or does not match. Does anyone know why that is happening based on the code I have?
Part 2. Is there a way to refactor my passConfirm function? I tried doing it by adding it to the validateForm function (Please see commented code for my example). It wasn't working tho.
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
event.preventDefault();
var name = document.regForm.FullName.value;
var email = document.regForm.email.value;
var phone = document.regForm.phone.value;
var password = document.regForm.Password.value;
var confirmPassword = document.regForm.ConfirmPassword.value;
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var nameError = emailError = phoneError = passwordError = true;
//Empty name input error message
if (name == "") {
printError("nameError", "Please enter your name")
}
//Empty email input error message
if (email == "") {
printError("emailError", "Please enter a valid email")
}
//Empty phone input error message
if (phone == "") {
printError("phoneError", "Please enter your phone numnber")
}
//Non valid phone number error messsage
if (phone.match(phoneno)) {
return true;
} else {
printError("phoneError", "Please enter a valid phone number")
}
//Empty Password input
if (password == "") {
printError("passwordError", "Please enter a password")
}
//Empty Cofirm Password input
if (confirmPassword == "") {
printError("confirmpassError", "Please confirm your password")
}
//I tried refactoring the passConfirm function and additing it here.
//if (password.match(confirmPassword)) {
// printPass("matchingPassword", "Passwords match")
// document.getElementById("matchingPassword").style.color = "green";
//} else {
// printPass("matchingPassword", "Passwords do no match")
// document.getElementById("matchingPassword").style.color = "red";
//}
};
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("matchingPassword").style.color = "green";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords match!"
} else {
document.getElementById("matchingPassword").style.color = "red";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords do NOT match!"
}
}
fieldset {
width: 420px;
height: 950px;
}
<h1>Hello, please register!</h1>
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm(event)">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<span class="error" id="nameError"></span>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<span class="error" id="emailError"></span>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
<span class="error" id="phoneError"></span>
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
<span class="error" id="passwordError"></span>
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
<span class="error" id="confirmpassError"></span>
</div>
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
Your button disappears because you use InnerHTML method to display the message, which overrides it. Though your logic works after passwords match when you press enter, you lose your button element. It is better to use a separate div or paragraph tag to display your message and keep your button as it is since it's part of the form.
Here is the change you can try
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button></span>
<p id="message"></p>
</fieldset>
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 match!"
}
}
I'm starting simple JavaScript form validation. I write two statement, first if statement working well but second one is not. But this two if statement separately working. I don't understand what I'm wrong. Here is the HTML code:
<form id="loginForm" name="loginForm" method="post" action="my-profile.html">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="eMail" placeholder="abcde00#example.com" class="form-control" required="required" />
<span class="erRor" id="error1">Please input valid email address</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="Password" name="password" id="pasSword" class="form-control" required="required" />
<span class="erRor" id="error2">Invalid email and password</span>
<span class="erRor" id="error3">This field should not be empty</span>
</div>
<div class="form-group">
<button type="submit" onclick="return validate();">Login</button>
</div>
</form>
JavaScript code here:
function validate(){
/* email validation */
var changeColor = document.getElementById("eMail");
var error1 = document.getElementById("error1");
var email1 = document.loginForm.email;
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!re.test(email1.value)){
changeColor.style.border = "2px solid red";
error1.style.display = "block";
return false;
}
/* empty fild check for password field */
var pas = document.getElementById("pasSword");
var error3 = document.getElementById("error3");
var password = document.loginForm.password;
if(password.value === ""){
pas.style.border = "2px solid red";
error3.style.display = "block";
return false;
}
}
Please help me out of this.
Note: I want to learn "AS YOU TYPE JavaScript for validation". I haven't find any proper tutorial or desiccation.
You are using return false, hence second validation is not working.
Try this:
var valid = true;
if(conditoin_one){
valid = false;
// update error element
}
if(conditoin_two){
valid = false;
// update error element
}
return valid;