I made a small script for when someone clicks on this eye image the input type was changed from ''password'' to ''text''
function mostrarocultarsenha() {
var senha = document.getElementById("senha")
if (senha.type == "password") {
senha.type = "text";
} else {
senha.type = "password"
}
}
<div class="campo">
<label for="password"><strong>Senha</strong></label>
<input type="password" name="senha" id="senha" required></input>
</div>
<img class="olho" id="olho" src="https://via.placeholder.com/100" onclick="mostrarocultarsenha()">
Photo from my website
I want that when the input changes from password to text, the image also changes from an eye to an eye with a scratch, and then if clicked again, go back to normal eye, does anyone know how I can do this?
const olho = document.querySelector("#olho")
if (senha.type === "password") {
senha.setAttribute("type", "text")
olho.src = "image link/path"
} else {
senha.setAttribute("type", "password")
olho.src = "another image link/path"
}
w3schools
basically it's just a element ID src it's actually really simple
<div class="campo">
<label for="password"><strong>Senha</strong></label>
<input type="password" name="senha" id="senha" required></input>
</div>
<a onclick="mostrarocultarsenha()"><img class="olho" id="olho" src="assets/closedEye.png"/></a>
function mostrarocultarsenha() {
var senha = document.getElementById("senha")
if (senha.type == "password") {
senha.type = "text";
document.getElementById("olho").src = "assets/openedEye.png";
} else {
senha.type = "password"
document.getElementById("olho").src = "assets/closedEye.png";
}
}
Related
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>
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>
I am new to javascript and DOM manipulation. So I have this form I have created basically to get names of players. What I want to achieve is to get the player names and display them on the games page once they are redirected after clicking on the button. It does not display the line of code and returns an error:
(VM4444:1 Uncaught ReferenceError: player1 is not defined at
:1:1).
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
console.log(player1, player2);
}
<div class="col-lg-4 col-md-4 col-sm-12 form">
<form>
<small class="form-text text-muted">We'll never share your details with anyone else.</small>
<div class="form-group">
<label for="player1">Player 1</label>
<input type="text" class="form-control" id="play1" aria-describedby="play1help">
</div>
<div class="form-group">
<label for="player1">Player 2</label>
<input type="text" class="form-control" id="play2" aria-describedby="play1help">
</div>
</form>
<button class="btn btn-lg btn-primary btn-block mt-3" onclick="next();">Start</button>
</div>
Using localStorage you can easily achieve this,
localStorage["key"] = value;
In next page you can get the value by using
value = localStorage["key"];
First Page
function next() {
var player1 = document.getElementById('play1').value;
var player2 = document.getElementById('play2').value;
if (player1 === '' || player2 === '') {
document.getElementById("error").style.color = "red";
document.getElementById("error").innerHTML = "Please enter both names";
} else {
location.href = "game.html";
}
document.getElementById('name1').innerHTML = player1.value;
document.getElementById('name2').innerHTML = player2.value;
localStorage["player1"] = player1;
localStorage["player2"] = player2;
console.log(player1, player2);
}
Next Page
function getPlayer() {
player1 = localStorage["player1"];
player2 = localStorage["player2"];
console.log(player1,player2)
}
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.
I have been working on a project that requires me to toggle between showing and hiding the password in a password field.
The JS code I came up with is:
<script>
function text(item) {
if (document.getElementById('password').type = "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
</script>
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input type="password" id="password" />
For some reason, it works just fine when toggling between password -> text, but fails to do the opposite.
What am I doing wrong?
You are missing an = in the if condition
if(document.getElementById('password').type="password"){
^^^^
Should be
if(document.getElementById('password').type=="password"){
Otherwise it will assign the type password to the field and it will return true always
function text(item) {
if (document.getElementById('password').type == "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input id="password" type="password" />