How do I display the feedback message only for the focused field?

1

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>
    
asked by anonymous 29.06.2018 / 18:53

2 answers

1

Send to the function validarCampos the element being typed:

validarCampos($(this));

In the function you get the element as parameter:

var  validarCampos = function(e) {...

This focus event is dispatchable, just use the input event:

$('#form-cadastro input.form-control').on('input', function() {
   validarCampos($(this));                          
});

I also added a return false; in the campoIncorreto function, to stop the main function when the field is invalid.

I also optimized the campoCorreto and campoIncorreto functions by removing repetitions when using multiple methods for the same element.

Other explanations I put in the code:

$('#form-cadastro input.form-control').on('input', function() {
   validarCampos($(this));							
});

var  validarCampos = function(e) {
   var inps = $('#form-cadastro input');
   for(var x=0; x<inps.length; x++){
      var id = !e ? $(inps[x]) : $('#'+e.attr("id")); // o valor $('#'+e.attr("id")) é se o form for submetido
      if (id.val().length < 5) {
         return campoIncorreto(id.attr('id'), 'Campo '+id.attr('placeholder')+' preenchido incorretamente!');								
      } else { 				
         campoCorreto(id.attr('id'), 'Campo '+id.attr('placeholder')+' preenchido corretamente!');
      }
   }

   var valida = $('#form-cadastro input.is-valid').length; // conto o número de campos válidos
   return valida == 2 ? true : false; // e o número de campos válidos for igual a 2, envia
}
		
		
var campoCorreto = function(nome, texto) { 
   //campo input, usa-se sempre o id do elemento			
   $('#'+nome)
   .removeClass('is-invalid')
   .addClass('is-valid');
   
   //campo de feedback
   $('#feedback-'+nome)
   .removeClass('invalid-feedback')
   .addClass('valid-feedback')
   .text(texto)
   .show("slow");			
}

var campoIncorreto = function(nome, texto) {
   //campo input, usa-se sempre o id do elemento
   $('#'+nome)
   .removeClass('is-valid')
   .addClass('is-invalid');
   
   //campo de feedback
   $('#feedback-'+nome)
   .removeClass('valid-feedback')
   .addClass('invalid-feedback')
   .text(texto)
   .show("slow");
   
   return false;
}
div.main {
   margin:50px 16%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<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>
    
29.06.2018 / 19:46
0

You have to add a return when it is identified that the field is not valid.

if (nome.val() == "" || nome.val().length < 5) {    
                campoIncorreto('nome', 'Campo nome preenchido incorretamente!');                                
                return false;
            } else {                
                campoCorreto('nome', 'Campo nome preenchido corretamente!');                
            }
            if (email.val() == "" || email.val().length < 5) {
                campoIncorreto('email', 'Campo email preenchido incorretamente!');
                return false;
            } else {
                campoCorreto('email', 'Campo preenchido corretamente!');
            }
    
29.06.2018 / 19:47