How to activate event by clicking anywhere on the screen?

1

I have a CPF validation and this "event" is activated when I click the "validate" button.

I wanted this "event" to be activated when the user clicked off the input, as he typed the CPF and clicked and anywhere on the screen, then this validation "event" is activated without requiring any buttons. my code is like this:

<html>
<head>
  <title>Validar CPF com Máscara by TchekiGamer</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="language" content="PT-BR"/>

  <script src="http://www.geradorcpf.com/scripts.js"></script><scriptsrc="http://www.geradorcpf.com/jquery-1.2.6.pack.js"></script>
  <script src="http://www.geradorcpf.com/jquery.maskedinput-1.1.4.pack.js"></script><scripttype="text/javascript">$(document).ready(function(){  
    $("#cpf").mask("999.999.999-99");   

    $("#botaoValidarCPF").click(function() {       
      if($("#cpf").val() == '') {           
        $("#saida").html("Informe um CPF");         
        return false;   
      }    
      if(validarCPF($("#cpf").val())) {         
        $("#saida").html("<span style='color: green'>CPF Válido!</span>");     
      } 
      else {            
        $("#saida").html("<span style='color: red'>CPF Inválido!</span>");     }    });});
      </script>
    </head>

    <body>

      <form id="form1" name="form1" method="post" action="">

        <div align="center" id="saida1">
          <label>Digite o seu cpf</label>
          <input name="cpf" type="text" id="cpf"/> <!-- class="saida"-->
        </div>

        <div align="center">
          <input style="font-size: 15px; cursor: pointer" type="button" name="botaoValidarCPF" id="botaoValidarCPF" value="Validar CPF"/>
        </div>

        <div align="center" id="saida" class="style7"> <!-- aparece mensagem de CPF Invalido --></div>

      </form>
    </body>
    </html>
    
asked by anonymous 20.04.2018 / 14:41

2 answers

1

You can use the onblur event of the input, your code looks like this:

    $("#cpf").blur(function (){
    if($("#cpf").val() == '') {           
        $("#saida").html("Informe um CPF");         
        return false;   
    }    
    if(validarCPF($("#cpf").val())) {         
        $("#saida").html("<span style='color: green'>CPF Válido!</span>");     
    } 
    else {            
        $("#saida").html("<span style='color: red'>CPF Inválido!</span>");     
    } 
 });
    
20.04.2018 / 14:47
0

Solution 1

You can use the hasFocus () method, which will check if the input has focus, and if it does not, you do the validation.

Simple method use:

if (!objeto.hasFocus()) {
    //validação
}

Solution 2

You can validate while the user types by using an oninput event.

Simple Usage:

objeto.addEventListener("input", validarCPF);
    
21.04.2018 / 01:01