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.