I am performing a check using jquery
in order to apply this method to a more elaborate future project. There is no problem with the script, what I need is: When starting typing in the nome
field for example, the feedback appears only for it and not for others as it is occurring.
Below I am leaving the code as it will be easier to simulate, just type something in one of the fields and check that the feedback will appear for everyone, but the expected one is to appear only for the focused field.
$('#form-cadastro input').focus( function(){
$(this).on('input', function() {
validarCampos();
});
});
var nome = $('#nome');
var email = $('#email');
var validarCampos = function() {
var valido = true;
if (nome.val() == "" || nome.val().length < 5) {
campoIncorreto('nome', 'Campo nome preenchido incorretamente!');
valido = false;
} else {
campoCorreto('nome', 'Campo nome preenchido corretamente!');
}
if (email.val() == "" || email.val().length < 5) {
campoIncorreto('email', 'Campo email preenchido incorretamente!');
valido = false;
} else {
campoCorreto('email', 'Campo preenchido corretamente!');
}
if (valido == true) {
return true;
} else {
return false;
}
}
var campoCorreto = function(nome, texto) {
//campo input, usa-se sempre o id do elemento
$('#'+nome).removeClass('is-invalid');
$('#'+nome).addClass('is-valid');
//campo de feedback
$('#feedback-'+nome).removeClass('invalid-feedback');
$('#feedback-'+nome).addClass('valid-feedback');
$('#feedback-'+nome).text(texto).show("slow");
}
var campoIncorreto = function(nome, texto) {
//campo input, usa-se sempre o id do elemento
$('#'+nome).removeClass('is-valid');
$('#'+nome).addClass('is-invalid');
//campo de feedback
$('#feedback-'+nome).removeClass('valid-feedback');
$('#feedback-'+nome).addClass('invalid-feedback');
$('#feedback-'+nome).text(texto).show("slow");
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<style>
div.main {
margin:50px 16%;
}
</style>
<div class="container">
<div class="main col-8 offset-2">
<form id="form-cadastro" method="POST" action="https://www.google.com" onsubmit="return validarCampos()">
<input class="form-control" type="text" placeholder="nome" id="nome" />
<span id="feedback-nome"> </span> <br>
<input class="form-control" type="text" placeholder="email" id="email" />
<span id="feedback-email"></span> <br>
<input class="btn btn-outline-primary" type="submit" value="Enviar"/>
</form>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>