onkeyup vs onkeypress - Event pressing Space JavaScript key

0

onkeyup to check when we lift the key, instead onkeypress values the data when the key is pressed.

The problem I have is that my functionality works with onkeyup but with onkeypress does not work. I explain.

I have a evento to check key to key if there is or not the email that we enter in a " input " field in the database.

File verify_email.php:

<?php
    //Cabecera para indicar que vamos a enviar datos JSON y que no haga caché de los datos.
    header("Content-Type: application/json");
    header("Cache-Control: no-cache, must-revalidate");

    //Función que comprueba si existe o no un email.
    function mailExists($email) {
        $conexion = new PDO("mysql:host=localhost;dbname=osmarrural", "root", "root");
        $conexion->query("SET NAMES 'utf8'");
        $sql = "SELECT count(idemail) AS total FROM clientes WHERE idemail ='$email'";
        $datos = $conexion->query($sql);
        $registro = $datos->fetch();
        return $registro["total"];
    }

    //Si existe la variable/campo "idemail"...
    if(isset($_REQUEST["idemail"])){
        $respuesta = mailExists($_REQUEST["idemail"]);
        echo json_encode($respuesta);
    }else{
        $respuesta = -1;
        echo json_encode($respuesta);
    }
?>

Check_email feature:

function comprobar_email(e){
    var tecla = (document.all) ? e.keyCode : e.which;
    //Permitimos el acceso a una tecla "Space".
    if (tecla == 32){
        return false;
    }

    //Guardamos en una variable el valor del campo cuyo ID es "email".
    var caja_email = $("#email").val();
    //Llamamos por get/post al fichero que hemos creado para comprobar_email;
    $.get("comprobar_email.php", {idemail:caja_email}, function(resultado){
        //Si resultado==1, el email existe... color de fondo rojo y deshabilitar botón.
        if(resultado==1){
            $("#email").css({backgroundColor: '#EA0D0D'});
            $('#registrar').hide();
        }else{
            //Si resultado!=1, el email NO existe... color de fondo verde y habilitar botón.
            $("#email").css({backgroundColor: '#1EEA02'});
            $('#registrar').show();
        }
    });
}

Code that works:

<input type="text" name="idemail" id="email" placeholder="Email" onkeyup="return comprobar_email(event);">

Code that does not work:

 <input type="text" name="idemail" id="email" placeholder="Email" onkeypress="return comprobar_email(event);">

The problem that with onkeyup allows me to write " space " when I should press it. So if I change it to onkeypress , then " space " does press it, but I need to insert one more character of the account when I write the email to see if it exists or not . I hope you have explained to me.

    
asked by omaza1990 27.12.2017 в 22:41
source

1 answer

1

The problem is that you try to do everything at once when they are things that should be executed at different times.

On the one hand, you want the character to be checked before the character is written.

On the other hand you want that, once the character has been written, it is verified if the entered email exists.

The solution is obvious: separate the code and execute each function in a different event:

In the event keypress you check if the key pressed corresponds to a valid character and, if not, you cancel it.

In the event keyup you verify that the email entered is valid.

Here you have the example working. I have used jQuery to register the event handlers, and I have overwritten the get method of jQuery so that, instead of making the ajax request, it returns a result that the email exists only for '[email protected]' :

function checkValidKey(e){
  var tecla = document.all ? e.keyCode : e.which;
  return tecla !== 32;
}
function comprobar_email(e){
    //Guardamos en una variable el valor del campo cuyo ID es "email".
    var caja_email = $("#email").val();
    //Llamamos por get/post al fichero que hemos creado para comprobar_email;
    $.get("comprobar_email.php", {idemail:caja_email}, function(resultado){
        //Si resultado==1, el email existe... color de fondo rojo y deshabilitar botón.
        if(resultado==1){
            $("#email").css({backgroundColor: '#EA0D0D'});
            $('#registrar').hide();
        }else{
            //Si resultado!=1, el email NO existe... color de fondo verde y habilitar botón.
            $("#email").css({backgroundColor: '#1EEA02'});
            $('#registrar').show();
        }
    });
}

$(function(){
  // Registro controladores de eventos
  $('#email').on('keyup', comprobar_email);
  $('#email').on('keypress', checkValidKey);
  // Reemplazar llamada ajax
  // Únicamente devuelve que existe con '[email protected]'
  $.get = function(url, data, callback){
    callback(data.idemail === '[email protected]'?1:0);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <input type="text" name="idemail" id="email" placeholder="Email">
 
 <button id="registrar">Registrar</button>
    
answered by 28.12.2017 / 11:04
source