JSFiddle - React, Tailwind, and code Playground
by Burduja Serghei
HTML
<div class="container">
<form action="" class="myForm" method="post">
<input type="text" name="login" placeholder="login">
<input type="email" name="email" placeholder="email">
<input type="number" name="phone" placeholder="phone">
<input type="submit" value="submit">
<p class="result"></p>
</form>
</div>
CSS
input[type="text"],
input[type="email"],
input[type="number"] {
margin-right: 10px;
height: 30px;
text-indent: 15px;
line-height: 30px;
border: none;
}
input[type="text"].succes,
input[type="email"].succes,
input[type="number"].succes {
background: lightgreen;
}
input[type="text"].error,
input[type="email"].error,
input[type="number"].error {
background: lightpink;
}
input[type="submit"] {
padding: 8px 30px;
}
.result {
font-size: 20px;
}
.result.succes {
color: green;
}
.result.error {
color: red;
}
JavaScript
let inputCollection = document.querySelectorAll('input[type="email"], input[type="text"], input[type="number"]');
let myForm = document.querySelector('.myForm');
let result = document.querySelector('.result');
function isEmpty(el){
return el.value.length === 0;
}
myForm.onsubmit = function(){
let res = [];
let resultText = '';
for (let i = 0; i < inputCollection.length; i++) {
if (!isEmpty(inputCollection[i])) {
res.push(inputCollection[i]);
}else{
inputCollection[i].classList.remove('succes');
inputCollection[i].classList.add('error');
resultText += 'Missing datat for input ' + inputCollection[i].getAttribute('type') + '<br>';
}
}
result.classList.remove('succes');
result.classList.add('error');
result.innerHTML = resultText;
if(res.length === inputCollection.length){
result.classList.remove('error');
result.classList.add('succes');
result.innerHTML = 'Data was sent';
setTimeout(function(){
console.log('wait');
}, 2000);
}else{
return false;
}
};
for (let i = 0; i < inputCollection.length; i++) {
inputCollection[i].oninput = function(){
this.classList.remove('error');
this.classList.add('succes');
};
}