JSFiddle - React, Tailwind, and code Playground
by Dedi Wibisono
HTML
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="lala not-empty">
<input type="text" class="email" placeholder="email">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<br>
<button class="add">add</button>
<button class="validasi" onclick="validate();">validate</button>
CSS
.error{
display:none;
}
.show{
display:block !important
}
JavaScript
$(".not-empty").keypress(function(){
if ($(this).children('input').val().length < 3) {
$(this).children('input').css("color","red")
} else {
$(this).children('input').css("color","blue")
}
})
$(".add").click(function(){
$(".test").append(`
<div class="not-empty"><input type="text" placeholder="name" class="name" /><div class="error">error</div></div>
`)
})
function validate() {
let cekLengthError = 0;
let foundElemWithError = false;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
if (!foundElemWithError) { // only focus on first invalid field
foundElemWithError = true;
$(this).children('input:first').focus();
}
cekLengthError = cekLengthError + 1;
} else {
$(this).next().removeClass("show");
}
});
if (cekLengthError == 0) {
alert("success")
}
}