Form validation by pure JS - javascript

I am a stuck on following issues:
How to add required error just once after first click on submit button? And not at any subsequent click after.
How can to start function (checkValid()) with RegExp validation only after first function (checkRequired()) implementation with required checking?
How to show every error after RegExp validation in its relative element? Now all errors are displayed in the last block with phone input.
Here is case on jsfiddle:
https://jsfiddle.net/SanchezMalina/hno7v4tf/35/
Or code here:
// regexp pattern functions
function validateEmail(email) {
let 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,}))$/;
return re.test(email.toLowerCase());
}
function validatePhone(phone) {
let re = /^[0-9]{7,20}$/;
return re.test(phone.toLowerCase());
}
function validateName(name) {
let re = /^([a-zA-Z0-9А]){3,50}$/;
return re.test(name.toLowerCase());
}
let flag = false;
// check required fields
function checkRequired() {
let notFilled = document.querySelectorAll('.is-required');
notFilled.forEach(function (el) {
if (el.value === '') {
el.parentElement.classList.add('is-empty');
addRequiredError();
} else {
el.parentElement.classList.remove('is-empty');
removeRequiredError();
}
});
}
let formFields = document.querySelectorAll('.form__field');
//add required error message
function addRequiredError() {
let errorRequiredMsg = document.createElement('div');
errorRequiredMsg.classList.add('input-required');
errorRequiredMsg.innerHTML = `<span> This field is required! </span>`;
formFields.forEach( function (elem) {
if (elem.classList.contains('is-empty')) {
elem.appendChild(errorRequiredMsg);
}
});
}
//remove required error message
function removeRequiredError() {
let requiredErrorMsg = document.querySelectorAll('.form__field .input-required');
requiredErrorMsg.forEach(function (elem) {
elem.parentElement.removeChild(elem);
});
flag = true;
}
//check validation inputs
function checkValid() {
let firstName = document.querySelector('#f-name');
let lastName = document.querySelector('#l-name');
let selectCountry = document.querySelector('.form__select');
let phone = document.querySelector('#cell');
let email = document.querySelector('#email');
formFields.forEach(function () {
if(!validateName(firstName.value) && !validateName(lastName.value) && !validatePhone(phone.value) && !validateEmail(email.value)) {
firstName.parentElement.classList.add('is-error');
lastName.parentElement.classList.add('is-error');
selectCountry.parentElement.classList.add('is-error');
phone.parentElement.classList.add('is-error');
email.parentElement.classList.add('is-error');
addValidError();
} else {
firstName.parentElement.classList.remove('is-error');
lastName.parentElement.classList.remove('is-error');
selectCountry.parentElement.classList.remove('is-error');
phone.parentElement.classList.remove('is-error');
email.parentElement.classList.remove('is-error');
removeValidError();
}
});
}
//add invalid error message
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = `<span> Input is invalid! </span>`;
formFields.forEach(function (elem) {
if (elem.classList.contains('is-error')) {
elem.appendChild(errorValidMsg);
}
});
// for (let i = 0; i < formFields.length; i++) {
//
// if (formFields[i].classList.contains('is-error')) {
//
// formFields[i].appendChild(errorValidMsg);
//
// }
// }
}
//remove invalid error message
function removeValidError() {
let requiredErrorMsg = document.querySelectorAll('.input-error');
requiredErrorMsg.forEach(function (elem) {
elem.parentNode.removeChild(elem);
})
}
//form submit handler
let formTrial = document.querySelector('.form__main');
formTrial.addEventListener('submit', function (event) {
event.preventDefault();
checkRequired();
console.log(flag);
if(flag !== false) {
checkValid();
}
});
.form__main {
display: block;
margin: 25px auto;
width: 450px;
}
.form__field {
position: relative;
margin: 10px 0;
padding: 5px 15px;
background-color: #fff;
height: 50px;
}
.form__field_select::after {
content: "";
width: 0;
height: 0;
border: 7px solid transparent;
border-color: #000 transparent transparent transparent;
position: absolute;
top: 55%;
right: 17px;
transform: translateY(-50%);
}
.form__input {
position: absolute;
left: 0;
top: 10px;
right: 0;
bottom: 10px;
padding-left: 45px;
background: none;
font-size: 14px;
font-weight: 400;
font-family: "Open Sans", sans-serif;
width: 100%;
color: #333;
line-height: 1.714;
box-sizing: border-box;
}
.form__input:focus ~ .form__label,
.form__input:valid ~ .form__label {
top: 0;
left: 45px;
transform: scale(0.6, 0.6);
color: #000;
}
.form__input:focus ~ .form__label[for=cell],
.form__input:valid ~ .form__label[for=cell] {
top: 0;
left: 125px;
}
.form__input[type=tel] {
padding-left: 125px;
}
.form__input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 100px white inset;
}
.form__label {
position: absolute;
top: 50%;
left: 50px;
transform-origin: left top;
transition: all 0.3s ease;
transform: translateY(-50%);
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #999999;
line-height: 1.714;
}
.form__label[for=cell] {
left: 135px;
}
.form__select {
position: absolute;
width: 100%;
height: 100%;
top: 50%;
transform: translateY(-50%);
left: 0;
right: 0;
padding-left: 50px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
background-color: transparent;
border-color: #fff;
font-size: 14px;
font-family: "Open Sans", sans-serif;
color: #000;
line-height: 1.714;
}
.form__country-code {
position: absolute;
color: #000;
left: 50px;
font-size: 14px;
font-family: "Open Sans", sans-serif;
line-height: 2;
height: 100%;
top: 0;
bottom: 0;
display: flex;
align-items: center;
border-right: 1px solid;
padding-right: 20px;
z-index: 2;
}
.form .btn {
width: 100%;
margin: 20px 0;
}
.form .btn:hover {
transform: translateY(-5px);
box-shadow: 1px 3px 20px #c5f833;
}
<form method="post" class="form__main" novalidate>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="f-name" type="text" required>
<label class="form__label" for="f-name">First Name</label>
</div>
<div class="form__field">
<i class="icon icon-user"></i>
<input class="form__input is-required" id="l-name" type="text" required>
<label class="form__label" for="l-name">Last Name</label>
</div>
<div class="form__field">
<i class="icon icon-envelop"></i>
<input class="form__input" id="email" type="text" required>
<label class="form__label" for="email">Email</label>
</div>
<div class="form__field form__field_select">
<i class="icon icon-pin"></i>
<select class="form__select" name="country">
<option value="ro" selected>USA</option>
<option value="ua">India</option>
<option value="il">Spain</option>
</select>
</div>
<div class="form__field">
<i class="icon icon-phone"></i>
<span class="form__country-code">+10000</span>
<input class="form__input" id="cell" type="tel" required>
<label class="form__label" for="cell">Phone</label>
</div>
<button class="btn btn_lime">Try for free</button>
</form>

1)
if( !el.parentElement.classList.contains('is-empty') ) {
addRequiredError();
}
2)
not sure to understand the question
3)
function addValidError() {
let errorValidMsg = document.createElement('div');
errorValidMsg.classList.add('input-error');
errorValidMsg.innerHTML = '<span> Input is invalid! </span>';
formFields.forEach(function (elem) { // <-- here formFields is not defined
}

Related

Replaying CSS Animations

Been struggling hours now to find a solution for this.
I´m kinda new to JS so this is kinda tricky for me.
Was hoping someone here maybe had a bit of time to give me a solution.
Thanks.
If you click on the question mark (top right) it starts my animation to show the slider, and when you click the X it starts an animation to hide the slider.
I would like this to happen infinite. So when X has been clicked and the slider goes in, you can just click on the question mark and the slider pops up again, and so forth.
let press = document.getElementById("questionClick");
let show = document.getElementById("show");
let showOpt = document.getElementById("showSecond")
let hide = document.getElementById("exit");
let arrow = document.getElementById("nextArrow");
let info = document.getElementsByClassName("info");
show.classList.remove("info");
press.addEventListener("click", function () {
show.classList.add("info");
arrow.style.opacity = "0"
exit.style.opacity = "0"
setTimeout(function() {
exit.style.opacity = "100"
}, (400));
setTimeout(function() {
arrow.style.opacity = "100"
}, (1300));
});
hide.addEventListener("click", function () {
showOpt.style.width = "0em"
show.classList.add("infoExit");
hide.style.opacity = "40%"
setTimeout(function() {
arrow.style.opacity = "0"
}, (00));
setTimeout(function() {
exit.style.opacity = "0"
}, (800));
});
arrow.addEventListener("click", function() {
showOpt.style.width = "15em"
showOpt.style.height = "668px"
showOpt.style.padding = "1em"
});
const resultEl = document.getElementById('result');
const lengthEl = document.getElementById('length');
const uppercaseEl = document.getElementById('uppercase');
const lowercaseEl = document.getElementById('lowercase');
const numbersEl = document.getElementById('numbers');
const symbolsEl = document.getElementById('symbols');
const generateEl = document.getElementById('generate');
const clipboard = document.getElementById('clipboard');
const randomFunc = {
lower: getRandomLower,
upper: getRandomUpper,
number: getRandomNumber,
symbol: getRandomSymbol
}
clipboard.addEventListener('click', () => {
const textarea = document.createElement('textarea');
const password = resultEl.innerText;
if(!password) { return; }
textarea.value = password;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
alert('Password copied to clipboard');
});
generate.addEventListener('click', () => {
const length = +lengthEl.value;
const hasLower = lowercaseEl.checked;
const hasUpper = uppercaseEl.checked;
const hasNumber = numbersEl.checked;
const hasSymbol = symbolsEl.checked;
resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, length);
});
function generatePassword(lower, upper, number, symbol, length) {
let generatedPassword = '';
const typesCount = lower + upper + number + symbol;
const typesArr = [{lower}, {upper}, {number}, {symbol}].filter(item => Object.values(item)[0]);
// Doesn't have a selected type
if(typesCount === 0) {
return '';
}
// create a loop
for(let i=0; i<length; i+=typesCount) {
typesArr.forEach(type => {
const funcName = Object.keys(type)[0];
generatedPassword += randomFunc[funcName]();
});
}
const finalPassword = generatedPassword.slice(0, length);
return finalPassword;
}
/* Generating random lower case characters */
function getRandomLower() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
/* Generating random upper case characters */
function getRandomUpper() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
/* Generating random numbers */
function getRandomNumber() {
return +String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}
/* Generating random symbols */
function getRandomSymbol() {
const symbols = '!##$%^&*(){}[]=<>/,.'
return symbols[Math.floor(Math.random() * symbols.length)];
}
.info {
animation: popup 1.6s;
animation-fill-mode:forwards;
}
#keyframes popup {
0% {
white-space: nowrap;
height: 4em;
width: 0em;
padding: 0.5em 1em 1em;
opacity: 0;
bottom: 13.9em; left: 9.7em;
color: rgba(0, 0, 0, 0);
}
40%, 50% {
width: 14em;
white-space: nowrap;
color: rgba(0, 0, 0, 0.555);
height: 4em;
padding: 0.5em 1em 1em;
opacity: 100;
bottom: 14em; left: 16.5em
}
60% {
white-space: normal;
}
90%, 100% {
height: 668px ;
width: 14em;
opacity: 100;
white-space: normal;
bottom: 0; left: 16.5em
}
}
.infoExit {
animation: popin 1.6s;
}
#exit {
padding: .3em .3em 0 0;
color: var(--clr-i-dim);
}
#exit:hover{
color: var(--clr-minibtn-inactive);
}
#keyframes popin {
0% {
height: 668px ;
width: 14em;
white-space: normal;
bottom: 0; left: 16.7em;
opacity: 100;
}
40%, 50% {
width: 14em;
white-space: nowrap;
height: 4em;
padding: 0.5em 1em 1em;
opacity: 100;
bottom: 14em; left: 16.5em;
}
50% {
white-space: nowrap;
color: rgba(0, 0, 0, 0.555);
}
80%, 100% {
white-space: nowrap;
height: 4em;
width: 0em;
padding: 0.5em 0em 1em;
opacity: 0;
bottom: 13.9em; left: 9.7em;
color: rgba(0, 0, 0, 0);
}
}
#infohead {
font-size: var(--fs-large);
font-weight: var(--fw-primary);
margin: 0.7em 0 0;
}
#show {
padding: 1em;
opacity: 0;
height: 668px ; width: 12em;
color: var(--txtclr-accent);
cursor: pointer;
font-size: var(--fs-info);
background: linear-gradient(45deg, #83b7da , #958bbb);
position: relative; left: 15.7em ; bottom: 0em; right: 0;
overflow: hidden;
border-radius: 0 .5em .5em 0;
}
#import url(https://fonts.googleapis.com/css?family=Montserrat);
#import url("https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700");
:root {
--ff-primary: 'Source Sans Pro', sans-serif;
--ff-accent: "Roboto", sans-serif;
--ff-option: "Open Sans", sans-serif;
--ff-number: 'Lato', sans-serif;
--fw-primary: 600;
--fw-accent: 400;
--fs-nomal: 1.2rem;
--fs-info: 1.3em;
--fs-large: 1.5rem;
--clr-primary: #50a3a2;
--clr-accent: #23235bdc;
--clr-white: rgba(255, 255, 255, 0.8);
--clr-btn: #530dc5;
--clr-btn-hover: #7031d4;
--clr-minibtn-hover: #4e694f;
--clr-minibtn-inactive: #943f3f;
--clr-shadow: 0px 5px 13px rgba(0, 0, 0, 0.993);
--clr-bg-primary: #4f65dd;
--clr-bg-accent: #aaa4a4 ;
--clr-i-dim: rgba(28, 28, 31, 0.637);
--txtclr-primary: rgba(255, 255, 255, 0.897);
--txtclr-accent: #212121 ;
}
* {
box-sizing: border-box;
}
html {
}
body {
background: var(--clr-primary);
color: var(--txtclr-primary);
font-family: var(--ff-primary);
display: flex; flex-direction: column;
align-items: center; justify-content: center;
min-height: 100vh;
background: -webkit-linear-gradient(top left, var(--clr-bg-primary) 0%, #ffffff 100%);
background: -moz-linear-gradient(top left, var(--clr-bg-primary) 0%, #ffffff 100%);
background: -o-linear-gradient(top left, var(--clr-bg-primary) 0%, #ffffff 100%);
background: linear-gradient(to bottom right, var(--clr-bg-primary) 0%, var(--clr-bg-accent) 100%);
}
h2 {
text-align: center;
margin: .2em 0 .8em;
}
h3 {
background: var(--clr-white);
color: var(--txtclr-accent);
font-family: var(--ff-option);
font-weight: var(--fw-accent);
line-height: 2rem;
}
label {
font-weight: var(--fw-primary);
font-family: var(--ff-option);
}
li {
margin: 1.8em 0;
list-style: none;
}
input {
cursor: pointer;
font-family: var(--ff-primary);
}
.container {
background: var(--clr-accent);
box-shadow: var(--clr-shadow);
position: absolute;
padding: 2em;
width:min(500px, 25em);
height: 668px;
}
.setting {
display: flex; justify-content: space-between; align-items: center;
}
.result-container {
background-color: rgba(168, 162, 162, 0.4);
display: flex; justify-content: flex-start; align-items: center;
position: relative;
font-size: var(--fs-nomal); letter-spacing: .14rem;
padding: 1em .6em; margin: 0 0 0.3em;
height: 2.6em;
}
.result-container #result {
word-wrap: break-word;
}
.result-container .btn {
font-size: 2rem;
position: absolute; top: 0.15em; right: 0.15em;
height: 1.3em; width: 1.3em;
}
.btn {
background: var(--clr-btn);
color: var(--txtclr-primary);
cursor: pointer;
border: none;
font-size: var(--fs-nomal);
padding: .6em;
}
.btn-large {
display: block;
width: 100%; height: 3.5em;
transition: .6s; overflow: hidden;
margin-top: 1.5em; border-radius: 4px;
transform: translateX(0%) translateY(0%);
}
#length {
height: 2.5em; width: 12em;
margin: 2em 0 1.7em; padding: 0 1em;
outline: 0;
color: var(--clr-bg-accent);
border: 0; border-radius: 5px;
outline: none;
cursor: pointer;
}
/* ICONS */
#questionClick, #exit, #exitOpt {
position: absolute; top: 0.3em; right: 0.3em;
}
#exit, #nextArrow {
transition: .2s; opacity: 0;
z-index: 999;
}
#nextArrow, #nextArrowOpt{
position: absolute; bottom: .4em; right: .4em;
}
#nextArrowOpt {
opacity: 100;
}
.far {
position: relative; bottom: 0.55em; right: 0.25em;
}
/* ICONS */
#keyframes jump {
0% {
top: 0.3em;
}
50% {
top: 0.32em;
}
100% {
top: 0.3em;
}
}
#showSecond {
position: absolute; left: 15.7em ; bottom: 0em; right: 0;
background: linear-gradient(45deg, #9fc4dd , #7d62dd);
opacity: 100;
white-space: normal;
height: 0px ; width: 0em;
cursor: pointer;
font-size: var(--fs-nomal); line-height: 1.5em;
position: relative; left: 19.2em ; bottom: 34.1em; right: 0;
overflow: hidden;
border-radius: 0 .5em .5em 0 ;
transition: 1s;
}
/* btn-large Effect */
button.btn-large:focus {
outline: 0;
}
button.btn-large:before {
content: '';
background: var(--clr-btn);
opacity: .5; filter: blur(30px);
transform: translateX(-100px) skewX(-15deg);
}
button.btn-large:after {
content: '';
display: block; position: absolute;
background: rgba(255, 255, 255, 0.2);
width: 30px; height: 100%;
left: 45px; top: 0;
opacity: 0; filter: blur(5px);
transform: translateX(-100px) skewX(-15deg);
}
button.btn-large:hover {
background: var(--clr-btn-hover);
}
button.btn-large:hover:before {
transform: translateX(300px) skewX(-15deg);
opacity: 0.6;
transition: .7s; }
button.btn-large:hover:after {
transform: translateX(300px) skewX(-15deg);
opacity: 1;
transition: .7s;
} /* btn-large Effect */
/* Mini button Effect */
.styled-checkbox {
position: absolute;
opacity: 100;
}
.styled-checkbox + label {
position: relative;
cursor: pointer;
padding: 0;
transition: 0.5s; }
.styled-checkbox + label:before {
content: '';
display: inline-block; vertical-align: text-top;
width: 20px; height: 20px;
background: var(--clr-minibtn-inactive); }
.styled-checkbox:hover + label:before {
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.342);
}
.styled-checkbox:focus + label:before {
box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.12); }
.styled-checkbox:checked + label:before {
background: var(--clr-minibtn-hover); }
.styled-checkbox:disabled + label {
color: #b8b8b8;
cursor: auto; }
.styled-checkbox:disabled + label:before {
box-shadow: none;
background: #ddd; }
.styled-checkbox:checked + label:after {
content: '';
position: absolute; left: 5px; top: 9px;
width: 2px; height: 2px;
background: white; box-shadow: 2px 0 0 white,
4px 0 0 white,
4px -2px 0 white,
4px -4px 0 white,
4px -6px 0 white,
4px -8px 0 white;
transform: rotate(45deg); }
/* Mini button Effect */
.range {
-webkit-appearance: none;
background: none;
}
.range::-webkit-slider-runnable-track {
background-color: #d7dbdd;
height: 6px;
border-radius: 3px;
border: 1px solid transparent;
}
.range::-ms-tooltip { display: none; /* display and visibility only */ }
.range::-webkit-slider-thumb {
-webkit-appearance: none;
border-radius: 100%;
background-color: #6574CF;
height: 18px;
width: 18px;
margin-top: -7px;
}
output {
min-width: 1em;
font-family: var(--ff-number);
font-size: 16px;
border-radius: 3px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="CS.css">
<script src="https://kit.fontawesome.com/79efab5353.js" crossorigin="anonymous"></script>
<script src="CS.js" defer></script>
<title>Document</title>
</head>
<body>
<div>
<h3 class="info" class="infoExit" id="show" class="show">
<span style = "">
<i id="exit" class="fas fa-times"></i>
</span>
<p id="infohead">Did you know?</p>
<br>
<br>
<b>6.850.000</b> passwords are getting hacked each day?
<br>
<br>
That is <b>158</b> each second!
<br>
<br>
Stop that from being you.
<br>
<br>
Let us help you make a strong password.
<span>
<i id="nextArrow" class="fas fa-chevron-circle-right"></i>
</span>
</h3>
</div>
<div class="container">
<h2>Password Generator</h2>
<div class="result-container">
<span id="result"></span>
<button class="btn" id="clipboard">
<section style = "font-size: 0.6em;">
<i class="far fa-clipboard"></i>
</section>
</button>
</div>
<span style = "font-size: 2em; color: rgb(209, 204, 214)">
<i id="questionClick" class="fas fa-question-circle"></i>
</span>
<div class="settings">
<div class="setting">
<label>Password length</label>
<input type="range" class="range" id="length" min='4' max='20' value='20' onmousemove="rangevalue1.value=value" />
<output id="rangevalue1"></output>
</div>
<div class="setting">
<label>Include uppercase letters</label>
<li>
<input class="styled-checkbox" id="uppercase" type="checkbox" value="value2" checked>
<label for="uppercase"></label>
</li>
</div>
<div class="setting">
<label>Include lowercase letters</label>
<li>
<input class="styled-checkbox" id="lowercase" type="checkbox" value="value2" checked>
<label for="lowercase"></label>
</li>
</div>
<div class="setting">
<label>Include numbers</label>
<li>
<input class="styled-checkbox" id="numbers" type="checkbox" value="value2" checked>
<label for="numbers"></label>
</li>
</div>
<div class="setting">
<label for="styled-checkbox-2">Include symbols</label>
<li>
<input class="styled-checkbox" id="symbols" type="checkbox" value="value2" checked>
<label for="symbols"></label>
</li>
</div>
</div>
<button class="btn btn-large" id="generate">
Generate password
</button>
<h3 id="showSecond">
<span style = "">
<i id="exitOpt" class="fas fa-times"></i>
</span>
<p id="infohead">What is a safe password?</p>
<br>
<br>
<b>7 characters</b> is normally the <b>minimum</b> length of a password with mixed symbols. <br><br>But it is highly recomended to use much more.
<br>
<br>
<b>The best possible password contains of 12 or more characters, mixed with symbols, numbers. lower & uppercase characters.</b>
<span>
<i id="nextArrowOpt" class="fas fa-chevron-circle-right"></i>
</span>
</h3>
</div>
</body>
</html>
Try using these function as below. Have updated the bare minimum.
press.addEventListener("click", function () {
show.classList.add("info");
show.classList.remove("infoExit");
arrow.style.opacity = "0"
exit.style.opacity = "0"
setTimeout(function() {
exit.style.opacity = "100"
}, (400));
setTimeout(function() {
arrow.style.opacity = "100"
}, (1300));
});
hide.addEventListener("click", function () {
setTimeout(function() {
show.classList.remove("info");
},1600);
showOpt.style.width = "0em"
hide.style.opacity = "40%"
show.classList.add("infoExit");
setTimeout(function() {
arrow.style.opacity = "0"
}, (00));
setTimeout(function() {
exit.style.opacity = "0"
}, (800));
});
I think your problem is your infoExit class that you don't remove after closing an idea would be to use maybe a toggle variable
//remove show.classList.remove("info");
let togglePress = false;
press.addEventListener("click", function () {
show.classList.remove("infoExit");
if (!togglePress) {
show.classList.add("info");
arrow.style.opacity = "0";
exit.style.opacity = "0";
setTimeout(function () {
exit.style.opacity = "100";
}, 400);
setTimeout(function () {
arrow.style.opacity = "100";
}, 1300);
togglePress = true;
}
})
hide.addEventListener("click", function () {
show.classList.remove("info");
if (togglePress) {
showOpt.style.width = "0em";
show.classList.add("infoExit");
hide.style.opacity = "40%";
setTimeout(function () {
arrow.style.opacity = "0";
}, 00);
setTimeout(function () {
exit.style.opacity = "0";
}, 800);
togglePress = false;
}
});
also you have several class attributes on your component which is not necessary
<h3 id="show">
<span id="exit">
<i class="fas fa-times"></i>
</span>
<p id="infohead">Did you know?</p>
<br />
<br />
<b>6.850.000</b> passwords are getting hacked each day?
<br />
<br />
That is <b>158</b> each second!
<br />
<br />
Stop that from being you.
<br />
<br />
Let us help you make a strong password.
<span>
<i id="nextArrow" class="fas fa-chevron-circle-right"></i>
</span>
</h3>

How to stop password field from showing 'null' as a placeholder?

I have a password field which is interactive and has some js going on behind the scenes. However I have this issue of when I click on the field, it shows 'null' as a value, as per the image.
This only shows when I click on the field, and I have no placeholder given to the input either. How do I prevent this from showing?
The code
//floating input controller
const FloatLabel = (() => {
// add active class
const handleFocus = (e) => {
const target = e.target;
target.parentNode.classList.add('active');
target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
};
// remove active class
const handleBlur = (e) => {
const target = e.target;
if (!target.value) {
target.parentNode.classList.remove('active');
}
target.removeAttribute('placeholder');
};
// register events
const bindEvents = (element) => {
const floatField = element.querySelector('input');
floatField.addEventListener('focus', handleFocus);
floatField.addEventListener('blur', handleBlur);
};
// get DOM elements
const init = () => {
const floatContainers = document.querySelectorAll('.float-container');
floatContainers.forEach((element) => {
if (element.querySelector('input').value) {
element.classList.add('active');
}
bindEvents(element);
});
};
return {
init: init
};
})();
FloatLabel.init();
.float-container {
position: relative;
background-color: #dfecff;
width: 100%;
border-radius: 5px;
transition: 150ms;
padding-top: .6em;
padding-bottom: .6em;
border: 2px solid #b9d6ff;
}
.float-container:hover {
background-color: #1a73e8;
cursor: text;
}
.password-toggle-button {
position: absolute;
font-size: 1em;
padding-top: 8px;
color: #333333;
margin-left: 93%;
}
.password-toggle-button:hover {
cursor: pointer;
color: #eeeeee;
}
label {
font-size: 1em;
font-family: Arial, Helvetica, sans-serif;
color: #5e5e5e;
position: absolute;
margin-left: 3%;
z-index: 140;
transform: translate(0, 0) scale(1);
pointer-events: none;
user-select: none;
transform-origin: top left;
transition: all .1s ease-in-out;
}
.float-container input {
color: #eeeeee;
}
.float-container.active label {
transform: translate(-0.5em, -1.5em) scale(.95);
font-style: italic;
font-weight: 200;
border-radius: 10px;
background-color: #1a73e8;
padding-left: .5em;
padding-right: .5em;
color: #eeeeee;
}
.float-container.active input {
color: #eeeeee;
}
.float-container.active {
background-color: #1a73e8;
border: 2px solid #eeeeee;
}
.form-center {
display: relative;
margin-top: 3em;
margin-left: 5vw;
margin-bottom: 5em;
word-break: break-all;
padding-top: 3%;
padding-left: 5vw;
padding-right: 3vw;
padding-bottom: 5%;
width: 60vw;
line-height: 2em;
background-color: #1a73e8;
border-radius: 20px;
border-width: 3px;
border-style: solid;
border-color: #333333;
}
input{
border: none;
background-color: transparent;
color: #333333;
outline: 0;
margin-top: auto;
margin-left: 3%;
margin-right: 20%;
width: 90%;
z-index: 150;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />
<div class="form-center"><div id="float-container" class="float-container" onclick="document.getElementById('pw').focus(); return false;">
<label for="pw" class="inner-label">Password</label>
<i class="fa fa-eye password-toggle-button" aria-hidden="true"></i>
<input type="password" class="floatField id="pw" placeholder="">
</div>
</div>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />
<div class="form-center"><div id="float-container" class="float-container" onclick="document.getElementById('pw').focus(); return false;">
<label for="pw" class="inner-label">Password</label>
<i class="fa fa-eye password-toggle-button" aria-hidden="true"></i>
<input type="password" class="floatField id="pw">
</div>
</div>
Have you tried removing the placeholder?
You have to verify if the value is null before setting it as the input placeholder:
const handleFocus = (e) => {
const target = e.target;
target.parentNode.classList.add('active');
const placeholder = target.getAttribute('data-placeholder');
if (!!placeholder && placeholder !== 'null') {
target.setAttribute('placeholder', placeholder);
} else {
// Do something else
}
};

Counter of submitted forms in php

I am trying to make a counter for submitting a form in php, if the data from the forms is sent to the server, +1 is written to the counter.txt file, this data is used to form the header in the letter. Everything works, but 5 identical letters come to the mail, the next time it sends 10 and so on. What is the problem? Why is this happening?
When I remove the counter code everything works fine and one letter arrives.
<?php
$email = ($_POST['sel']);
$change = ($_POST['button-set']);
$name = ($_POST['name']);
$question = ($_POST['message']);
$submit = ($_POST['submit']);
if (isset ($submit)) {
$count = file_get_contents ('counter.txt');
$count ++;
file_put_contents ('counter.txt', $count);
}
else {
$count = file_get_contents ('counter.txt');
};
$to = 'support#archsupport.ru';
$subject = 'Application number: ' . $count . 'from the site archsupport.ru';
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question ;
$headers = 'From: zergg52#gmail.com ' . "\r\n";
$subject = preg_replace("/(\r\n)|(\r)|(\n)/", "", $subject);
$subject = preg_replace("/(\t)/", " ", $subject);
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
#mail($to, $subject, $message, $headers);
echo 'message sent!';
var_dump($email,$change,$name,$question,$submit,$count)
?>
Page code:
var form = document.getElementsByTagName('form')[0];
var names = document.getElementById('name');
var validn = document.getElementById('vn');
var iconrequired = document.querySelector('#namereq');
var email = document.getElementById('sellection');
var valids = document.getElementById('vs');
var iconrequireds = document.querySelector('#sellectionreq');
var text = document.getElementById('qestions');
var validt = document.getElementById('vt');
var iconrequiredt = document.querySelector('#textreq');
document.addEventListener('input', function validation() {
var x = document.forms["support"]["sellection"].value;
if (names.validity.valid) {
validn.className = "valid";
iconrequired.className = "iconrequired hide";
};
if (email.validity.valid && x != "") {
valids.className = "valid";
iconrequireds.className = "iconrequired hide";
};
if (text.validity.valid) {
validt.className = "valid";
iconrequiredt.className = "iconrequired hide";
};
if (!names.validity.valid) {
validn.className = "invalid";
iconrequired.className = "iconrequired hide";
};
if (!email.validity.valid) {
valids.className = "invalid";
iconrequireds.className = "iconrequired hide";
};
if (!text.validity.valid) {
validt.className = "invalid";
iconrequiredt.className = "iconrequired hide";
};
if (names.validity.valid && email.validity.valid && text.validity.valid) {
$('#support').submit(function() {
$.post(
'https://www.archsupport.ru/post-email.php',
$("#support").serialize(),
function(msg) {
$('#support').hide('slow');
$('#message').html(msg);
}
);
});
} else {
return false;
}
});
function validateSellection() {
var x = document.forms["support"]["sellection"].value;
if (x === "") {
document.getElementById('sellectionreq').classList.remove("hide");
return false;
} else {
document.getElementById('sellectionreq').classList.add("hide");
return false;
}
};
function validateName() {
var x = document.forms["support"]["name"].value;
if (x === "") {
document.getElementById('namereq').classList.remove("hide");
return false;
} else {
document.getElementById('namereq').classList.add("hide");
return false;
}
};
function validateText() {
var x = document.forms["support"]["qestions"].value;
if (x === "") {
document.getElementById('textreq').classList.remove("hide");
return false;
} else {
document.getElementById('textreq').classList.add("hide");
return false;
}
};
$('#support').submit(function validate() {
if (validateName() && validateSellection() && validateText() === true) {
return false;
} else {
validateSellection();
validateName();
validateText()
return false
}
});
$(".radio").on('click.two', function() {
let input = $("#sellection");
if ($("#radio").prop("checked")) {
input.prop("disabled", false);
input.prop({
"type": "email",
"placeholder": "example#yourmail.ru",
"autocomplete": "email",
"maxlength": "35",
"minlength": "12",
"value": "",
});
document.getElementById("sellection").pattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$";
} else {
input.prop("disabled", false);
$("#sellection").prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
document.getElementById("sellection").pattern = "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}";
}
input.focus();
input.val("");
});
var fab = $('.icons');
fab.on('click.ten', function iconback() {
fab.removeClass('checked');
$(this).addClass('checked');
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/form.css">
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form novalidate action="" method="post" name="support" id="support">
<label class="required"><span id="vs" class="invalid hide"></span><input id="sellection" class="mail sellection" name="sel" vlaue="" placeholder="choose a communication way...." required disabled><span id="error1"></span><div id="sellectionreq" class="iconrequired hide">REQUIRED</div></label>
<div class="button-set">
<label title="Email"><img class="icons" src='/img/icon/social_icon_mail_white.svg'><input class="radio" id="radio" type="radio" name="button-set" value="to mail" style="display:none;"></label>
<label for="radio1" title="WhatsApp"><img class="icons" src='/img/icon/social_icon_whatsapp_white.svg'><input class="radio" id="radio1" type="radio" name="button-set" value="to WhatsApp" style="display:none;"></label>
<label for="radio2" title="Telegram"><img class="icons" src='/img/icon/social_icon_telegram_white.svg'><input class="radio" id="radio2" type="radio" name="button-set" value="to Telegram" style="display:none;"></label>
<label for="radio3" title="Viber"><img class="icons" src='/img/icon/social_icon_viber_white.svg'><input class="radio" id="radio3" type="radio" name="button-set" value="to Viber" style="display:none;"></label>
</div>
<label class="required"><span id="vn" class="invalid hide"></span>
<input id="name" class="mail" type="name" name="name" autocomplete= none placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="message" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="4" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="submit" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
</body>
<script src="/js/form.js"></script>
</html>
without counter:
var_dump($email,$change,$name,$question,$submit) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL
with counter:
var_dump($email,$change,$name,$question,$submit,$count) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL string(1) "9"
$count immediately takes on value "9"
site with form: https://www.archsupport.ru/
In regards to the HTML/JavaScript, consider the following code.
$(function() {
var form = $("#support");
function checkFieldValidity(fObj) {
var r = false;
var re = new RegExp(fObj.attr("pattern"));
var v = fObj.val();
if (fObj.is("[required]")) {
if (v.length) {
fObj.next(".iconrequired").hide();
} else {
fObj.next(".iconrequired").show();
}
if (re.test(v)) {
fObj.prev(".icon").removeClass("invalid").addClass("valid");
r = true;
} else {
fObj.prev(".icon").removeClass("valid").addClass("invalid");
}
} else {
r = true;
}
return r;
}
$("input", form).blur(function() {
checkFieldValidity($(this));
});
form.submit(function(e) {
e.preventDefault();
var valid = true;
$("[required]", form).each(function(i, el) {
valid = valid && checkFieldValidity($(el));
});
return valid;
});
$(".button-set label", form).on('click', function() {
$(this).parent().find(".checked").removeClass("checked");
$("img", this).addClass("checked");
var input = $("#sellection");
input.prop("disabled", false);
switch ($(this).data("value")) {
case "email":
input.prop({
type: "email",
placeholder: "example#yourmail.com",
autocomplete: "email",
maxlength: 35,
minlength: 12,
value: "",
}).attr("pattern", "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$");
break;
// Add Cases for each selection option if needed
default:
input.prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
input.attr("pattern", "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}");
break;
}
input.focus();
input.val("");
});
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form novalidate action="" method="post" name="support" id="support">
<span class="icon"></span><input id="sellection" class="mail" name="f[sel]" value="" placeholder="Choose a communication method...." required disabled>
<div class="iconrequired hide">REQUIRED</div>
<div class="button-set">
<label title="Email" data-value="email"><img class="icon" src='/img/icon/social_icon_mail_white.svg'></label>
<label title="WhatsApp" data-value="whatsapp"><img class="icon" src='/img/icon/social_icon_whatsapp_white.svg'></label>
<label title="Telegram" data-value="telegram"><img class="icon" src='/img/icon/social_icon_telegram_white.svg'></label>
<label title="Viber" data-value="viber"><img class="icon" src='/img/icon/social_icon_viber_white.svg'></label>
</div>
<label class="required"><span class="icon"></span>
<input id="name" class="mail" type="name" name="f[name]" autocomplete="none" placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="f[message]" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="45" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="f[submit]" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
You want to evaluate if each field that is required has content and matches a specific pattern. I think your approach was too complicated. Additionally, I would stick with all native JavaScript or all jQuery. Don't mix them.
For submit, you will want to test each field and keep a running tally. To do this, you can logically start with a true value and as you test, keep logically evaluating. Example:
var result = true;
result = result && true; // result is true
result = result && false; // result is false
result = result && true; // result is false
If some of the fields validate and if any do not, the result will be false and the form should not submit. If all validate, the result will be true and it's safe to submit the data to PHP. This should also prevent multiple submissions.
Remember that this is Client Side validation and can be bypassed by posting the data manually to the PHP. Most users will not even bother, yet all it takes is one curious or malicious User or Bot to see that they can bypass the form and create their own HTTP Post Payload. So you will want to ensure that your PHP is protected from such actions. Test any data submitted by the User before using it in your PHP Code. For example, you define $name like so:
$name = ($_POST['name']);
If I construct a payload like:
&name=;include "/etc/passwd";
This might get evaluated in the following code:
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question;
Just some things to consider.

Validation and button problem before next page

I am creating a multi form.
When I do not input any words and click the next button, the system has a display function validation but it also goes to next page automaticly.
So, what I need todo, is detect when I input a wrong format or empty string, so the system will make a validation and not automaticly go to the next page.
Finally, how can I click the submit button have the system save all my form data?
Here's is my script:
function page1() {
var name = document.forms["form1"]["name"].value
var email = document.forms["form1"]["email"].value
if (name == "" || !isNaN(name)) {
alert("Please enter correct name");
return false;
}
if (email.match(/^[\w\d._-]+#[\w\d.-]+\.[\w\d]{2,6}$/)) {
} else {
alert("Please enter correct email");
return false;
}
}
function page2() {
var phone = document.forms["form1"]["phone"].value
var address = document.forms["form1"]["address"].value
if (address == "" || !isNaN(address)) {
alert("Please enter correct address");
return false;
}
if (phone == "" || phone.length <= 9 || phone.length > 13 || isNaN(phone)) {
alert("Please enter correct phone");
return false;
}
return true;
}
function page3() {
var password = document.forms["form1"]["password"].value
var password2 = document.forms["form1"]["password"].value
if (password.match(/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{8,15})/)) {
} else {
alert("Please enter correct password");
return false;
}
if (password1 != password2) {
alert("Password and Re-enter Password was not same");
return false;
}
return true;
}
$(document).ready(function() {
$(".form-wrapper .button1").click(function() {
$(this).closest("form1").find("input[type=text], input[type=password]").val("");
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").next().addClass("is-active");
headerSection.removeClass("is-active").next().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
submit = $(this);
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
$(document).ready(function() {
$(".form-wrapper .button2").click(function() {
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").prev().addClass("is-active");
headerSection.removeClass("is-active").prev().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
this.submit();
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
background-color: #fff;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #fff;
font-weight: 200;
}
a {
text-decoration: none;
}
p,
li,
a {
font-size: 14px;
}
fieldset {
margin: 0;
padding: 0;
border: none;
color: #fff;
}
/* GRID */
.twelve {
width: 100%;
}
.eleven {
width: 91.53%;
}
.ten {
width: 83.06%;
}
.nine {
width: 74.6%;
}
.eight {
width: 66.13%;
}
.seven {
width: 57.66%;
}
.six {
width: 49.2%;
}
.five {
width: 40.73%;
}
.four {
width: 32.26%;
}
.three {
width: 23.8%;
}
.two {
width: 15.33%;
}
.one {
width: 6.866%;
}
/* COLUMNS */
.col {
display: block;
float: left;
margin: 0 0 0 1.6%;
}
.col:first-of-type {
margin-left: 0;
}
.container {
width: 100%;
max-width: 700px;
margin: 0 auto;
position: relative;
}
.row {
padding: 20px 0;
}
/* CLEARFIX */
.cf:before,
.cf:after {
content: " ";
display: table;
}
.cf:after {
clear: both;
}
.cf {
*zoom: 1;
}
.wrapper {
width: 100%;
margin: 30px 0;
}
/* STEPS */
.steps {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #000;
text-align: center;
}
.steps li {
display: inline-block;
margin: 20px;
color: #ccc;
padding-bottom: 5px;
}
.steps li.is-active {
border-bottom: 1px solid #fff;
color: #fff;
}
/* FORM */
.form-wrapper .section {
padding: 0px 20px 30px 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
background-color: #000;
opacity: 0;
-webkit-transform: scale(1, 0);
-ms-transform: scale(1, 0);
-o-transform: scale(1, 0);
transform: scale(1, 0);
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-ms-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
text-align: center;
position: absolute;
width: 100%;
min-height: 300px
}
.form-wrapper .section h3 {
margin-bottom: 30px;
}
.form-wrapper .section.is-active {
opacity: 1;
-webkit-transform: scale(1, 1);
-ms-transform: scale(1, 1);
-o-transform: scale(1, 1);
transform: scale(1, 1);
}
.form-wrapper .button1,
.form-wrapper .submit {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
right: 20px;
bottom: 20px;
}
.form-wrapper .button2 {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
left: 20px;
bottom: 20px;
}
.form-wrapper .submit {
border: none;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.form-wrapper input[type="text"],
.form-wrapper input[type="password"] {
display: block;
padding: 10px;
margin: 10px auto;
background-color: #f1f1f1;
border: none;
width: 50%;
outline: none;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<div class="container">
<div class="wrapper">
<ul class="steps">
<li class="is-active">Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ul>
<form class="form-wrapper" id="form1" onsumbit="return submit1()">
<fieldset class="section is-active">
<h3>Your Details</h3>
<input type="text" name="name" id="name" placeholder="Name">
<input type="text" name="email" id="email" placeholder="Email">
<input class="button1" type="button" value="Next" onclick="return page1()">
</fieldset>
<fieldset class="section">
<h3>other Details</h3>
<input type="text" name="phone" id="phone" placeholder="Phone">
<input type="text" name="address" id="address" placeholder="address">
<input class="button2" type="button" value="Previous">
<input class="button1" type="button" value="Next" onclick="return page2()">
</fieldset>
<fieldset class="section">
<h3>Choose a Password</h3>
<input type="password" name="password" id="password" placeholder="Password">
<input type="password" name="password2" id="password2" placeholder="Re-enter Password">
<input class="button2" type="button" value="Previous">
<input class="submit button1" type="submit" value="Sign Up" onclick="return page3()">
</fieldset>
<fieldset class="section">
<h3>Account Created!</h3>
<p>Your account has now been created.</p>
<div class="button1">Reset Form</div>
</fieldset>
</form>
</div>
</div>
You do not need onclick event on the button of the page1, page2, page3.
remove onclick="return page1()" call the functions
Just use one event onclick and it should work, add classes to check the validations, this is what I did.
if ($(this).hasClass('page1')) {
if (!page1()) {
return;
}
}
else if ($(this).hasClass('page2')) {
if (!page2()) {
return;
}
}
else if ($(this).hasClass('page3')) {
if (!page3()) {
return;
}
}
function page1() {
var name = document.forms["form1"]["name"].value
var email = document.forms["form1"]["email"].value
if (name == "" || !isNaN(name)) {
alert("Please enter correct name");
return false;
}
if (email.match(/^[\w\d._-]+#[\w\d.-]+\.[\w\d]{2,6}$/)) {
} else {
alert("Please enter correct email");
return false;
}
return true;
}
function page2() {
var phone = document.forms["form1"]["phone"].value
var address = document.forms["form1"]["address"].value
if (address == "" || !isNaN(address)) {
alert("Please enter correct address");
return false;
}
if (phone == "" || phone.length <= 9 || phone.length > 13 || isNaN(phone)) {
alert("Please enter correct phone");
return false;
}
return true;
}
function page3() {
var password = document.forms["form1"]["password"].value
var password2 = document.forms["form1"]["password"].value
if (password.match(/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{8,15})/)) {
} else {
alert("Please enter correct password");
return false;
}
if (password1 != password2) {
alert("Password and Re-enter Password was not same");
return false;
}
return true;
}
$(document).ready(function() {
$(".form-wrapper .button1").click(function() {
if ($(this).hasClass('page1')) {
if (!page1()) {
return;
}
}
else if ($(this).hasClass('page2')) {
if (!page2()) {
return;
}
}
else if ($(this).hasClass('page3')) {
if (!page3()) {
return;
}
}
$(this).closest("form1").find("input[type=text], input[type=password]").val("");
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").next().addClass("is-active");
headerSection.removeClass("is-active").next().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
submit = $(this);
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
$(document).ready(function() {
$(".form-wrapper .button2").click(function() {
var button = $(this);
var currentSection = button.parents(".section");
var currentSectionIndex = currentSection.index();
var headerSection = $('.steps li').eq(currentSectionIndex);
currentSection.removeClass("is-active").prev().addClass("is-active");
headerSection.removeClass("is-active").prev().addClass("is-active");
$(".form-wrapper").submit(function(e) {
e.preventDefault();
this.submit();
});
if (currentSectionIndex === 3) {
$(document).find(".form-wrapper .section").first().addClass("is-active");
$(document).find(".steps li").first().addClass("is-active");
}
});
});
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
background-color: #fff;
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: #fff;
font-weight: 200;
}
a {
text-decoration: none;
}
p,
li,
a {
font-size: 14px;
}
fieldset {
margin: 0;
padding: 0;
border: none;
color: #fff;
}
/* GRID */
.twelve {
width: 100%;
}
.eleven {
width: 91.53%;
}
.ten {
width: 83.06%;
}
.nine {
width: 74.6%;
}
.eight {
width: 66.13%;
}
.seven {
width: 57.66%;
}
.six {
width: 49.2%;
}
.five {
width: 40.73%;
}
.four {
width: 32.26%;
}
.three {
width: 23.8%;
}
.two {
width: 15.33%;
}
.one {
width: 6.866%;
}
/* COLUMNS */
.col {
display: block;
float: left;
margin: 0 0 0 1.6%;
}
.col:first-of-type {
margin-left: 0;
}
.container {
width: 100%;
max-width: 700px;
margin: 0 auto;
position: relative;
}
.row {
padding: 20px 0;
}
/* CLEARFIX */
.cf:before,
.cf:after {
content: " ";
display: table;
}
.cf:after {
clear: both;
}
.cf {
*zoom: 1;
}
.wrapper {
width: 100%;
margin: 30px 0;
}
/* STEPS */
.steps {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #000;
text-align: center;
}
.steps li {
display: inline-block;
margin: 20px;
color: #ccc;
padding-bottom: 5px;
}
.steps li.is-active {
border-bottom: 1px solid #fff;
color: #fff;
}
/* FORM */
.form-wrapper .section {
padding: 0px 20px 30px 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
background-color: #000;
opacity: 0;
-webkit-transform: scale(1, 0);
-ms-transform: scale(1, 0);
-o-transform: scale(1, 0);
transform: scale(1, 0);
-webkit-transform-origin: top center;
-moz-transform-origin: top center;
-ms-transform-origin: top center;
-o-transform-origin: top center;
transform-origin: top center;
-webkit-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
text-align: center;
position: absolute;
width: 100%;
min-height: 300px
}
.form-wrapper .section h3 {
margin-bottom: 30px;
}
.form-wrapper .section.is-active {
opacity: 1;
-webkit-transform: scale(1, 1);
-ms-transform: scale(1, 1);
-o-transform: scale(1, 1);
transform: scale(1, 1);
}
.form-wrapper .button1,
.form-wrapper .submit {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
right: 20px;
bottom: 20px;
}
.form-wrapper .button2 {
background-color: #fff;
display: inline-block;
padding: 8px 30px;
color: #000;
cursor: pointer;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
position: absolute;
left: 20px;
bottom: 20px;
}
.form-wrapper .submit {
border: none;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.form-wrapper input[type="text"],
.form-wrapper input[type="password"] {
display: block;
padding: 10px;
margin: 10px auto;
background-color: #f1f1f1;
border: none;
width: 50%;
outline: none;
font-size: 14px !important;
font-family: 'Open Sans', sans-serif !important;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<div class="container">
<div class="wrapper">
<ul class="steps">
<li class="is-active">Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ul>
<form class="form-wrapper" id="form1" onsumbit="return submit1()">
<fieldset class="section is-active">
<h3>Your Details</h3>
<input type="text" name="name" id="name" placeholder="Name">
<input type="text" name="email" id="email" placeholder="Email">
<input class="button1 page1" type="button" value="Next">
</fieldset>
<fieldset class="section">
<h3>other Details</h3>
<input type="text" name="phone" id="phone" placeholder="Phone">
<input type="text" name="address" id="address" placeholder="address">
<input class="button2" type="button" value="Previous">
<input class="button1 page2" type="button" value="Next" onclick="return page2()">
</fieldset>
<fieldset class="section">
<h3>Choose a Password</h3>
<input type="password" name="password" id="password" placeholder="Password">
<input type="password" name="password2" id="password2" placeholder="Re-enter Password">
<input class="button2" type="button" value="Previous">
<input class="submit button1 page3" type="submit" value="Sign Up" onclick="return page3()">
</fieldset>
<fieldset class="section">
<h3>Account Created!</h3>
<p>Your account has now been created.</p>
<div class="button1">Reset Form</div>
</fieldset>
</form>
</div>
</div>
by doing this you will be able to apply your code easily and you do not have to find multiple places to be appear.

How to make the simon game work properly

I'm working on the "Simon Game" project.
I want it to lighten buttons in the proper sequence. But now by far the code works properly until the 2-nd level.
If I am right the checkButton(randIndexArr, counter) should be included to the promise, so that if counter === index then it should call checkButton and maybe there are some more errors that I missed.
Here's a link with the video: How the code should work to be more clear Zipline: Build a Simon Game
and here is my code:
document.addEventListener("DOMContentLoaded", function () {
'use strict';
var checkOn = document.querySelector("input[type=checkbox]");
var gameCount = document.getElementsByClassName("innerCount")[0];
var startButton = document.getElementById("innerStart");
var strictButton = document.getElementById("strictButton");
var strictInd = document.getElementById("strictIndicator");
var strictMode = false;
var soundArray = document.getElementsByTagName("audio");
var buttons = document.querySelectorAll(".bigButton");
var buttonArray = [].slice.call(buttons, 0);
checkOn.addEventListener("change", function () {
if (checkOn.checked) {
gameCount.innerHTML = "--";
} else {
gameCount.innerHTML = "";
}
});
strictButton.addEventListener("click", function () {
strictMode = !strictMode;
strictMode ? strictInd.style.backgroundColor = "#FF0000" :
strictInd.style.backgroundColor = "#850000";
});
function getRandArray() {
var array = [];
for (var i = 0; i < 22; i++) {
array[i] = Math.floor(Math.random() * 4);
}
document.getElementsByClassName("randArray")[0].innerHTML = array;
return array;
}
startButton.addEventListener("click", function () {
var level = 0;
var randIndexArr = getRandArray();
playGame(randIndexArr, level);
});
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
function checkButton(randIndexArr, counter) {
console.log('checkButton');
var checker = function checker(e) {
var clickedButtonId = e.target.dataset.sound;
lightenButton(clickedButtonId);
sleep(1000);
for (let index = 0; index <= counter; index++) {
if (+(clickedButtonId) === randIndexArr[index]) {
if (index === counter) {
console.log('checking passed - next level :', (counter + 1));
counter++;
for (var i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
playGame(randIndexArr, counter);
}
}
}
}
;
for (var i = 0; i < 4; i++) {
buttonArray[i].addEventListener("click", checker, false)
}
}
function playGame(randIndexArr, counter) {
if (counter === 22) {
return;
}
//Show the level of the Game
gameCount.innerHTML = counter + 1;
//Light and play random buttons according to the level
//Light and play user's input then check if input is correct
randIndexArr.slice(0, counter + 1).reduce(function (promise, div, index) {
return promise.then(function () {
console.log("slice reduce");
lightenButton(div);
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("reduce Resolve");
}, 1000);
})
})
}, Promise.resolve()).then(function (value) {
console.log(value);
checkButton(randIndexArr, counter);
});
}
function lightenButton(id) {
var lightColorsArr = ["liteGreen", "liteRed", "liteYell", "liteBlue"];
var promise = new Promise((resolve, reject) => {
soundArray[id].play();
buttonArray[id].classList.add(lightColorsArr[id]);
setTimeout(function () {
resolve("lighten");
}, 500);
});
promise.then(function (value) {
console.log(value);
buttonArray[id].classList.remove(lightColorsArr[id]);
});
}
});
#font-face {
font-family: myDirector;
src: url('https://raw.githubusercontent.com/Y-Taras/FreeCodeCamp/master/Simon/fonts/myDirector-Bold.otf');
}
#outerCircle {
display: flex;
flex-wrap: wrap;
margin: 0 auto;
width: 560px;
border: 2px dotted grey;
position: relative;
}
.bigButton {
height: 250px;
width: 250px;
border: solid #464646;
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: background-color 0.5s ease;
}
#greenButton {
background-color: rgb(9, 174, 37);
border-radius: 100% 0 0 0;
border-width: 20px 10px 10px 20px;
}
.liteGreen#greenButton {
background-color: #86f999;
}
#redButton {
background-color: rgb(174, 9, 15);
border-radius: 0 100% 0 0;
border-width: 20px 20px 10px 10px;
}
.liteRed#redButton {
background-color: #f9868a;
}
#yellowButton {
background-color: rgb(174, 174, 9);
border-radius: 0 0 0 100%;
border-width: 10px 10px 20px 20px;
}
.liteYell#yellowButton {
background-color: #f9f986;
}
#blueButton {
background-color: rgb(9, 37, 174);
border-radius: 0 0 100% 0;
border-width: 10px 20px 20px 10px;
}
.liteBlue#blueButton {
background-color: #8699f9;
}
div#innerCircle {
border: 15px solid #464646;
border-radius: 50%;
position: absolute;
top: 25%;
right: 25%;
background-color: #c4c7ce;
}
div.additionalBorder {
margin: 4px;
border-radius: 50%;
height: 242px;
width: 242px;
overflow: hidden;
}
p#tradeMark {
margin: auto;
height: 104px;
text-align: center;
font-size: 68px;
font-family: myDirector;
color: #c4c7ce;
background-color: black;
border-color: antiquewhite;
line-height: 162px;
}
span#reg {
font-size: 12px;
}
.partition {
height: 6px;
}
.buttons {
height: 128px;
border-radius: 0 0 128px 128px;
border: 2px solid black;
}
/* Start and Strict buttons*/
table {
margin-left: 5px;
}
td {
text-align: center;
width: auto;
padding: 2px 10px;
vertical-align: bottom;
}
div.innerCount {
width: 54px;
height: 40px;
background-color: #34000e;
color: crimson;
border-radius: 11px;
font-size: 28px;
line-height: 42px;
text-align: center;
font-family: 'Segment7Standard', italic;
}
button#innerStart {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: #a50005;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div.strict {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
button#strictButton {
width: 27px;
height: 27px;
border: 4px solid #404241;
border-radius: 50%;
background: yellow;
box-shadow: 0 0 3px gray;
cursor: pointer;
}
div#strictIndicator {
width: 6px;
height: 6px;
margin-bottom: 2px;
background-color: #850000;
border-radius: 50%;
border: 1px solid #5f5f5f;
}
#switcher {
display: flex;
justify-content: center;
align-items: center;
}
.labels {
font-family: 'Roboto', sans-serif;
margin: 4px;
}
/* toggle switch */
.checkbox > input[type=checkbox] {
visibility: hidden;
}
.checkbox {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
border: 2px solid #424242;
}
.checkbox > label {
position: absolute;
width: 30px;
height: 26px;
top: 2px;
right: 2px;
background-color: #a50005;
cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
right: 28px;
}
<div id="outerCircle">
<div class="bigButton" id="greenButton" data-sound = "0" >0
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"></audio>
</div>
<div class="bigButton" id="redButton" data-sound = "1">1
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3" ></audio>
</div>
<div class="bigButton" id="yellowButton" data-sound = "2">2
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"></audio>
</div>
<div class="bigButton" id="blueButton" data-sound = "3">3
<audio src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"></audio>
</div>
<div id="innerCircle">
<div class="additionalBorder">
<p id="tradeMark">simon<span id="reg">®</span></p>
<div class="partition"></div>
<div class="buttons">
<table>
<tr class="firstRow">
<td>
<div class="innerCount"></div>
</td>
<td>
<button type="button" id="innerStart"></button>
</td>
<td>
<div class="strict">
<div id="strictIndicator"></div>
<button type="button" id="strictButton"></button>
</div>
</td>
</tr>
<tr class="labels">
<td>
<div id="countLabel">COUNT</div>
</td>
<td>
<div id="startLabel">START</div>
</td>
<td>
<div id="strictLabel">STRICT</div>
</td>
</tr>
</table>
<div id="switcher">
<span class="labels">ON</span>
<div class="checkbox">
<input id="checkMe" type="checkbox">
<label for="checkMe"></label>
</div>
<span class="labels">OFF</span>
</div>
</div>
</div>
</div>
</div>
<div class="randArray"></div>
One of the problem (along many others) is in checkButton function itself, where you checking buttons against array, but doesn't check the series of button presses, or "attempts".
For example, if randIndexArr contains values [2,2,1,1...], your code is okay with checking clickeBbuttonId with value 2 against both array's first two values, and so on.
I did rewrote only one function checkButton just to show you one of possible approaches:
var currentAttempt = 1
function checkButton(randIndexArr, counter) {
var checker = function checker(e) {
var clickedButtonId = e.target.dataset.sound;
lightenButton(clickedButtonId);
if (randIndexArr[currentAttempt -1] === +(clickedButtonId)){
if (currentAttempt - 1 === counter) {
counter++
currentAttempt = 1
for (var i = 0; i < 4; i++) {
buttonArray[i].removeEventListener("click", checker, false)
}
playGame(randIndexArr, counter);
}
currentAttempt++
} else {
currentAttempt = 1
}
};
for (var i = 0; i < 4; i++) {
buttonArray[i].addEventListener("click", checker, false)
}
}
But to be honest, whole code should be redesigned.

Categories