A message box won't appear when using an onclick event - javascript

I am trying to show a message box for password validation when clicking on an input type password field. i want the message box to show as soon as i click on the password field.
So far, if i run the page and click on the password input field, i would have to click in, click out then click in again just for the message box to appear. I can't really pinpoint the error here since im fairly new to Javascript and HTML.
I am using visual studio code for the IDE and it doesnt appear to show any errors when i run so it has to be an internal issue.
my code is :
function getPassword() {
var myInput = document.getElementById("psw");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
the input type code is as follows:
<label for="psw"><b>Password:</b></label> <br>
<input id = "psw" name="psw" type="password" onblur=" getPassword();"/> <br>
<input type="button" value="check password" class="checkpsw">
My CSS code is :
input {
width: 50%;
padding: 6px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}
input[type=radio]{
position:absolute;
line-height: 2px;
}
input[type=checkbox]{
position:absolute;
line-height: 2px;
}
/* Style the button */
input[type=button] {
background-color: #04AA6D;
color: white;
}
.checkpsw {
background-color: #0fabb6;
color: white;
}
/* Style the container for inputs */
.container {
background-color: #f1f1f1;
padding: 20px;
}
/* The message box is shown when the user clicks on the password field */
#message {
display:none;
background: #f8f8f8;
color: #000;
position: relative;
padding: 15px;
margin-top: 10px;
width:50%;
}
#message p {
padding: 10px 35px;
font-size: 18px;
}
/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}
.valid:before {
position: relative;
left: -35px;
content: "\2714";
}
/* Add a red text color and an "x" icon when the requirements are wrong */
.invalid {
color: red;
}
.invalid:before {
position: relative;
left: -35px;
content: "\2716";
}

Use the myInput.onfocus = function() outside of the getPassword function block.

You need to modify your code in this way. It will solve your problem. Basically, when you go to the password field it will be focus So anything you want to do at that time. You can do like if you want to change the border color on the focus you can do it as well.
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
function getPassword() {
var myInput = document.getElementById("psw");
var number = document.getElementById("number");
var length = document.getElementById("length");
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}

Related

How to display customized output based on field values

So my aim is to create a pop up modal where one could click to enter their regional school code in a text or number field to see if they are eligible for the files posted or not.
for example, if your code is 11002, you should get the recommended message else the apology message also I would like to have a button that can prompt user to go back and enter a new code if the last one is not accepted. This should all be on the same page.
Below is my code so far but I wish to display the result in a span as plain text not as in a field.
<style>
#result {
width: 100%;
}
#btn1 {
float: right;
}
</style>
<script>
function locationlookup() {
var result = document.getElementById("areacode").value;
var schooling;
if (result == 11002) {
schooling = "Great! Your school is eligible for this course";
} else if (result == 11003) {
schooling = "Great! Your school is eligible for this course";
} else if (result == 11004) {
schooling = "Your school is eligible but you need good conduct certificate";
} else {
schooling = "Sorry. we currently do not serve in your entered location";
}
document.getElementById("result").value = schooling;
}
</script>
<table align="center">
<tr>
<th>School Area code: <input type="text" name="areacode" id="areacode" >
<button onclick="locationlookup()" id="btn1">Lookup</button>
</th>
</tr>
<tr>
<th>
<input type="text" name="result" id="result" readonly></th>
<!-- I wish to change the above field to a span so no limitations. but stuff don't
work for me -->
</tr>
</table>
Maybe something like following snippet:
const input = document.querySelector("#areacode")
const span = document.querySelector("#result")
const btn = document.querySelector("#btnTryAgain")
function locationlookup() {
const result = input.value;
let schooling;
let results = [11002, 11003, 11004]
if (results.includes(Number(result))) {
schooling = "Great! Your school is eligible for this course"
} else {
schooling = "Sorry. we currently do not serve in your entered location"
btn.classList.toggle('hideBtn')
}
span.innerText = schooling;
}
function tryAgain() {
input.value = ''
span.innerText = '';
btn.classList.toggle('hideBtn')
input.focus()
}
#result {
width: 100%;
}
#btn1 {
float: right;
}
.hideBtn {
display: none;
}
<table align="center">
<tr>
<th>School Area code: <input type="text" name="areacode" id="areacode" >
<button onclick="locationlookup()" id="btn1">Lookup</button>
</th>
</tr>
<tr>
<th>
<span id="result"></span>
<button onclick="tryAgain()" id="btnTryAgain" class="hideBtn btn">Try again</button>
</th>
</tr>
</table>
So I found the below walk around to the problem which is quite handy but I will like to use that of Nikola if it finally works.
here is the code.
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function locationlookup() {
var result = document.getElementById("areacode").value;
var locality;
if (result == 11002) {
locality = "Great! Your school is eligible for this course";
} else if (result == 11003) {
locality = "Great! Your school is eligible for this course";
} else if (result == 11004) {
locality = "Your school is eligible but you need good conduct certificate and more whatever text for the coding";
} else {
locality = "Sorry. we currently do not serve in your entered location";
}
const el = document.querySelector('div[contenteditable]');
el.addEventListener('input', () => console.log(el.textContent));
el.textContent = locality;
}
/* Button used to open the contact form - fixed at the bottom of the page */
.open-button {
background-color: black;
color: white;
padding: 5px 5px;
border: none;
cursor: pointer;
opacity: 1;
}
.spanishly3 {
text-align: left;
}
.spanishly2 {
float: right;
}
.bold2 {
font-size: 16px;
}
.spanishly3:before {
content: "";
display: block;
background: url("icon.png") no-repeat;
width: 20px;
height: 20px;
float: left;
margin: 0 6px 0 0;
}
/* The popup form - hidden by default */
.form-popup {
display: none;
position: fixed;
/*bottom: 50%;*/
right: 50%;
border: 3px solid #f1f1f1;
z-index: 9;
}
/* Add styles to the form container */
.form-container {
max-width: 500px;
padding: 10px;
background-color: white;
}
/* Full-width input fields */
.form-container input[type=text], .form-container input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
border: none;
background: #f1f1f1;
}
/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus {
background-color: #ddd;
outline: none;
}
/* Set a style for the submit/login button */
.form-container .btn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
border: none;
cursor: pointer;
width: 100%;
margin-bottom:10px;
opacity: 0.8;
}
/* Add a red background color to the cancel button */
.form-container .cancel {
background-color: red;
}
/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {
opacity: 1;
}
div[contenteditable] {
border: 1px solid black;
width: 300px;
border: none;
font-weight: bold;
}
<button class="open-button" onclick="openForm()"><div class="spanishly2"><span class="spanishly3" style="align: left;">hello</span><p><b class="bold2">Select Your Address</b></p></div></button>
<div class="form-popup" id="myForm">
<form action="/action_page.php" class="form-container">
Area code: <input type="text" name="areacode" id="areacode" placeholder="00000">
<button onclick="locationlookup()" id="btn1">Lookup</button>
<div contenteditable></div>
<p><i>or login to set/use your location</i></p>
<br>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
Manage addresses
</form>
</div>

JS Problem with Multiple Forms working using 1 JS file

This is following on from:
JS Form validation Checkbox IF statement not working
I've added another separate form for the business owners.
Currently I have a separate html file for 'business' & 'customer'. I've put the CSS for both forms in one file and also the JS is all in one file.
Problem : I seem to only be able to get one form to work at the moment, although if I take the forms out and separate them into different projects they work fine, independently, on different platforms or workspaces.
What I'm trying to do is get the one JS file to reference both forms & execute commands based on what page the user is on filling out the form (business or customer). The problem is only Customer Form works when the JS is all in one file, the Business Form doesn't work (ie show the red highlighted errors). If I take the Business Form out and put it in another stand alone project (inc the HTML, CSS & JS) it works fine. Seems to be a conflict with the Form reference?
I need 2 forms as I will be expanding on fields etc, but to keep things simple I've thrown up samples of both on here.
Here is the HTML for the 'Business' form, (customer form HTML is in the link -and yes it has been changed to work properly):
<div class="business-contactus-body">
<div class="business_container">
<div class="business_contactus_heading_form">
<h2>Business client Form</h2>
</div>
<form id="business_contactus_form" class="business_contactus_form">
<div class="business-form-control">
<label for="businessName">Name</label>
<input type="text" placeholder="ABC Company" id="businessName" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<label for="businessEmail">Email</label>
<input type="text" placeholder="a#abccompany.com" id="businessEmail" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<label for="businessMessage">Message</label>
<textarea type="text" placeholder="Please enter a brief message" id="businessMessage" cols="30" rows="10"></textarea>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="business-form-control">
<input class="businessDisclaimerBox" type="checkbox" id="businessDisclaimerBox" />
<label for="businessDisclaimerBox" id="disclaimer-label">I agree to the terms and conditions.</label>
<small>Error message</small>
</div>
<button class="contactus_form_button">Submit</button>
</form>
</div>
</div>
CSS - for both forms
/***** CONTACT US PAGE CSS *****/
* {
box-sizing: border-box;
}
.customer-contactus-body, business-contactus-body {
min-height: 1300px;
width: 100%;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin: 0px;
}
.customerCU-contactus-heading-message, .business-contactus-heading-message {
width: 600px;
font-weight: 200;
margin: -50px 0px 50px 20px;
padding: 0px;
}
.customerCU_container, .business_container {
background-color: grey;
border-radius: 5px;
overflow: hidden;
width: 600px;
max-width: 100%;
}
.customer_contactus_heading_form, .business_contactus_heading_form {
border-bottom: 1px solid #f0f0f0;
background-color: white;
padding: 20px 40px;
}
.customer_contactus_heading_form h2, .business_contactus_heading_form h2 {
margin: 0px;
color: black;
}
.contactus_form, .business_contactus_form {
padding: 30px 40px;
}
.customerCU-form-control, .business-form-control {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}
.customerCU-form-control label, .business-form-control label {
display: inline-block;
margin-bottom: 5px;
font-weight: 530;
font-size: 17px;
}
.customerCU-form-control input, .business-form-control input {
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
font-size: 14px;
padding: 10px;
width: 100%;
}
.customerCU-form-control input:focus, .business-form-control input:focus {
outline: 0;
border-color: grey;
}
.customerCU-form-control.success input, .business-form-control.success input {
border-color: green;
}
.customerCU-form-control textarea, .business-form-control textarea {
resize: vertical;
border: 2px solid #f0f0f0;
border-radius: 4px;
display: block;
font-size: 14px;
padding: 10px;
width: 100%;
}
.customerCU-form-control.error input, .business-form-control.error input {
border-color: red;
}
.customerCU-form-control textarea:focus, .business-form-control textarea:focus {
outline: 0;
border-color: grey;
}
.customerCU-form-control.success textarea, .business-form-control.success textarea {
border-color: green;
}
.customerCU-form-control.error textarea, .business-form-control.error textarea {
border-color: red;
}
.customerCU-form-control.error label#disclaimer-label, .business-form-control.error label#disclaimer-label {
color: red;
font-weight: bold;
text-decoration: underline;
}
.customerCU-form-control i, .business-form-control i {
visibility: hidden;
position: absolute;
top: 40px;
right: 10px;
}
.customerCU-form-control.success i.fa-check-circle, .business-form-control.success i.fa-check-circle {
color: green;
visibility: visible;
}
.customerCU-form-control.error i.fa-exclamation-circle, .business-form-control.error i.fa-exclamation-circle {
color: red;
visibility: visible;
}
.customerCU-form-control small, .business-form-control small {
color: red;
position: absolute;
bottom: 0;
left: 0;
visibility: hidden;
}
.customerCU-form-control.error small, .business-form-control.error small {
visibility: visible;
}
label#disclaimer-label {
margin-left: 10px;
font-size: 12px;
width: 612px;
}
.contactus_form_button {
background-color: rgb(31, 136, 229);
border: 2px solid rgb(128, 128, 128, 0.199);
border-radius: 4px;
color: #fff;
display: block;
font-size: 16px;
padding: 10px;
margin-top: 20px;
width: 100%;
cursor: pointer;
transition: 0.3s ease background-color;
}
.contactus_form_button:hover {
cursor: pointer;
box-shadow: 1px 1px 1px rgb(25, 60, 173);
}
#keyframes contactus-form-status {
0% {
opacity: 1;
pointer-events: all;
}
90% {
opacity: 1;
pointer-events: all;
}
100% {
opacity: 0;
pointer-events: none;
}
}
JS
//** CUSTOMER FORM **//
const form = document.getElementById('contactus_form');
const customerName = document.getElementById('customerName');
const customerCUEmail = document.getElementById('customerCUEmail');
const disclaimerBox = document.getElementById('disclaimerBox');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const customerNameValue = customerName.value.trim();
const customerCUEmailValue = customerCUEmail.value.trim();
if(customerNameValue === '') {
setErrorFor(customerName, 'Please enter your name');
} else {
setSuccessFor(customerName);
}
if(customerCUEmailValue === '') {
setErrorFor(customerCUEmail, 'Email cannot be blank');
} else if (!isEmail(customerCUEmailValue)) {
setErrorFor(customerCUEmail, 'Not a valid email');
} else {
setSuccessFor(customerCUEmail);
}
if(!disclaimerBox.checked == true){
setErrorFor(disclaimerBox, 'Please check box and accept our terms and conditions.');
}else {
setSuccessFor(disclaimerBox);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'customerCU-form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'customerCU-form-control success';
}
function isEmail(customerCUEmail) {
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(customerCUEmail);
}
// ** BUSINESS CLIENT FORM **
const business_contactus_form = document.getElementById('business_contactus_form');
const businessName = document.getElementById('businessName');
const businessEmail = document.getElementById('businessEmail');
const businessMessage = document.getElementById("businessMessage");
const businessDisclaimerBox = document.getElementById('businessDisclaimerBox');
business_contactus_form.addEventListener('submit', e => {
e.preventDefault();
checkbusiness_Inputs();
});
function checkbusiness_Inputs() {
//trim to remove the whitespaces
const businessNameValue = businessName.value.trim();
const businessEmailValue = businessEmail.value.trim();
const businessMessageValue = businessMessage.value.trim();
if (businessNameValue === '') {
setErrorForB(businessName, 'Please enter your name');
} else {
setSuccessForB(businessName);
}
if (businessEmailValue === '') {
setErrorForB(businessEmail, 'Email cannot be blank');
} else if (!isEmailB(businessEmail)) {
setErrorForB(businessEmail, 'Not a valid email');
} else {
setSuccessForB(businessEmail);
}
if (businessMessageValue === '') {
setErrorForB(businessMessage, 'Please enter a message.');
} else {
setSuccessForB(businessMessage);
}
if (!businessDisclaimerBox.checked) {
setErrorForB(businessDisclaimerBox, 'Please check box and accept terms and conditions.');
} else {
setSuccessForB(businessDisclaimerBox);
}
}
function setErrorForB(input, message) {
const formControlB = input.parentElement;
const small = formControlB.querySelector('small');
formControlB.className = 'business-form-control error';
small.innerText = message;
}
function setSuccessForB(input) {
const formControlB = input.parentElement;
formControlB.className = 'business-form-control success';
}
function isEmailB(businessEmail) {
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(businessEmail);
}

Remove An Element When One Exists

I'm back with my nooby Javascript questions. I'm working on form validation and I'm adding text to check if a name was inputted. The problem I'm running into is if I don't put a name but then I do, the message for not putting a name shows up with the other element and vice versa but im looking for a way to make it dissapear when another element is chosen. Is there some sort of way of preventing an element from showing when one is present? I appreciate you guys/girls taking time out of your day to help a noob out haha. :)
Code:
var complete = document.getElementById('button');
complete.addEventListener('click', validate);
function validate() {
var textBox = document.getElementById('name');
var red = document.getElementById('nah');
var green = document.getElementById('yah');
if (textBox.value === '') {
red.style.display = 'block';
} else {
green.style.display = 'block';
}
}
#nah {
display: none;
color: red;
}
#yah {
color: green;
display: none;
}
button {
display: block;
margin-top: 50px;
border: 0.1px solid red;
background: red;
color: white;
font-size: 30px;
padding: 10px;
cursor: pointer;
}
<input type="text" id="name">
<p id="nah">Please Enter Name!</p>
<p id="yah">Thank you!</p>
<button id="button">Complete Form</button>
When you show one message you need to hide the other one.
var complete = document.getElementById('button');
complete.addEventListener('click', validate);
function validate() {
var textBox = document.getElementById('name');
var red = document.getElementById('nah');
var green = document.getElementById('yah');
if (textBox.value === '') {
red.style.display = 'block';
green.style.display = 'none';
} else {
green.style.display = 'block';
red.style.display = 'none';
}
}
#nah {
display: none;
color: red;
}
#yah {
color: green;
display: none;
}
button {
display: block;
margin-top: 50px;
border: 0.1px solid red;
background: red;
color: white;
font-size: 30px;
padding: 10px;
cursor: pointer;
}
<input type="text" id="name">
<p id="nah">Please Enter Name!</p>
<p id="yah">Thank you!</p>
<button id="button">Complete Form</button>
Simplest way is to just hide the other messages during validation:
function validate() {
var textBox = document.getElementById('name');
var red = document.getElementById('nah');
var green = document.getElementById('yah');
if (textBox.value === '') {
red.style.display = 'block';
green.style.display = 'none'; //hide the other element
} else {
green.style.display = 'block';
red.style.display = 'none'; //hide the other element
}
}
You could do it in a more sophisticated way using data attributes to control visibility, but this is probably a good start.

The alert for wrong password keeps displaying, even after I click ok using Javascript. How do I stop this continuous display of the alert message

I've been trying to validate a password text in a Modal window. When I enter the the incorrect password the alert keeps on displaying "Login is incorrect" message. Seems the while loop I am using, keeps continuing. How do I make the alert message display only once. But the Modal window should keep displaying
var modal = document.getElementById('loginModal');
// Get the button that opens the modal
var btn = document.getElementById("loginBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
function promptPassword( )
{
while (document.getElementById("pwdText").value != 'P#ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
alert("Password is correct, you are allowed to enter the site");
}
.modal {
display: none; /* Modal not shown by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the modal box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 25%;
height: 25%;
}
/*Display of text box labels*/
label{
display: inline-block;
float: left;
clear: left;
width: 250px;
text-align: left;
}
label {
display: inline-block;
float: left;
}
/*Display of text and password boxes*/
input[type=text] {
width:250px;
}
input[type=password] {
width:250px;
}
/* Close Button */
.close {
float: right;
margin: -15px -15px 0 0;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
text-decoration: none;
cursor: pointer;
}
<!-- Login button to pen Modal box -->
<button id="loginBtn">Login</button>
<!-- The Modal box-->
<div id="loginModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form>
<br/>
<label>User Name</label><input id="userName" type="text"><br />
<br/>
<label>Password</label><input id="pwdText" type="password"><br />
<br/>
<button onclick="promptPassword()">Submit</button>
</form>
</div>
I need to do this without using Jquery
function promptPassword( )
{
if (document.getElementById("pwdText").value != 'P#ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
Use if instead of while
First you need to replace
<button onclick="promptPassword()">Submit</button>
to
<button onclick="return promptPassword()">Submit</button>
Then you need to use only this
function promptPassword( )
{
var pwd = document.getElementById("pwdText").value;
if(pwd != 'P#ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
return false;
}
else{
alert("Password is correct, you are allowed to enter the site");
// Enter Site Code Here
}
}
You're using a while loop, which will keep repeating until the condition is no longer met.
What you need is an if statement.
function promptPassword( ) {
if(document.getElementById("pwdText").value != 'P#ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
}
function promptPassword( ) {
if(document.getElementById("pwdText").value != 'P#ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
return false;
}
}

Hide the validation output mark (✘) symbol hide when page is loaded/reloaded

I use the code below with HTML5 pattern matching on the input boxes and the CSS3 :invalid and :valid pseudo-selectors to display the output of the validation (valid value or not) in the div.input-validation available next to the input box. This works as expected but it displays the validation mark (✘ - invalid input) during page load itself and on re-loading the page. How should I avoid this?
Code:
<style type="text/css">
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"]:valid {
color: green;
}
input[type="text"]:valid ~ .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"]:invalid ~ .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: inline-block;
}
</style>
<?echo $passwordregister;?>
<input name="pw" autocomplete="off" type="text" id="pw" pattern="[a-zA-Z0-9]{6,22}" autofocus required >
<div class="input-validation"></div>
You can hide the invalid value (✘) symbol on page load using either one of the following options.
Option 1: Hide the span which contains the symbol on page load and display it only when some keypress event has happened on the input text box.
window.onload = function() {
var el = document.querySelectorAll("input[type='text']");
for (var i = 0; i < el.length; i++) {
el[i].onkeypress = showSymbol;
}
function showSymbol() {
this.nextElementSibling.style.display = "inline-block"; // display the span next to the input in which key was pressed.
}
}
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"]:valid {
color: green;
}
input[type="text"]:valid + .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"]:invalid + .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: none;
}
<input name="pw" autocomplete="off" type="text" id="pw" class="new" pattern="[a-zA-Z0-9]{6,22}" autofocus required/> <span class="input-validation"></span>
Option 2: Define the CSS rules based on the presence of certain class (say visited) and assign this class only when some key is pressed in the input box.
window.onload = function() {
var el = document.querySelectorAll("input[type='text']");
for (var i = 0; i < el.length; i++) {
el[i].onkeypress = showSymbol;
}
function showSymbol() {
this.classList.add("visited"); // add the visited class
}
}
input {
font-size: 1em;
padding: .3em;
border-radius: 3px;
margin: .2em;
}
input[type="text"].visited:valid {
color: green;
}
input[type="text"].visited:valid + .input-validation::before {
content: "\2714";
color: green;
}
input[type="text"].visited:invalid + .input-validation::before {
content: "\2718";
color: red;
}
.input-validation {
display: inline-block;
}
<input name="pw" autocomplete="off" type="text" id="pw" class="new" pattern="[a-zA-Z0-9]{6,22}" autofocus required/> <span class="input-validation"></span>
Note:
I have replaced the ~ in your CSS selectors with + because ~ selects all siblings which match the selector whereas the + selects only the adjacent sibling. Using ~ would make the span next to all input boxes get displayed (when you have multiple input boxes in the form) as soon as you type a value in the first.
I have also modified the .input-validation from div to span but that is more of a personal preference and you can just retain the original div itself without any difference in functionality.

Categories