How to activate event by clicking anywhere on the screen?

Asked

Viewed 569 times

1

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

I wanted this "event" to be activated when the user clicks off the input, like he typed the CPF and clicked and anywhere on the screen, then this "validation event" is activated without the need for 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>
  <script src="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>

  <script type="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>

2 answers

1


You can use the onblur input event, your code would look 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>");     
    } 
 });

0

Solution 1

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

Simple use of the method:

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

Solution 2

You can validate while the user type, using an oninput event.

Simple use:

objeto.addEventListener("input", validarCPF);

Browser other questions tagged

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