How to show the feedback message only for the focused field?

Asked

Viewed 67 times

1

I’m performing a scan using jquery with the intention of applying this method in a more elaborate future project. There is no problem with the script, what I need is: When you start typing in the field nome for example, the feedback appears only to him and not to others as is happening.

Below I am leaving the code because it will be easier to simulate, just type something in some of the fields and check that the feedback will appear for all, but expected 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>

2 answers

1


Send to the function validarCampos the element being typed:

validarCampos($(this));

In the function you receive the element as parameter:

var  validarCampos = function(e) {...

That event focus is expendable, just use only the event input:

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

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

I also optimized the functions campoCorreto and campoIncorreto 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>
<script src="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>

  • I had done it this way, but it allows Submit even though it is outside the standard set in the rules

  • 1

    I realized, I’m rewriting the code.

  • 1

    Look now. I had to make drastic changes because I was conflicting with Ubmit and typing it into the field. Two events using the same function is complicated.

  • Very good, thank you :D

  • one more question: var inps = $('input', '#form-cadastro'); = var inps = $( '#form-cadastro input'); ?

  • True, it’s the same thing. I changed the answer.

  • thanks for the reply :)

Show 2 more comments

0

You have to add a Return when identified which 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!');
            }
  • If I put Return, it will validate only the first field to be entered

Browser other questions tagged

You are not signed in. Login or sign up in order to post.