Question:
I'm developing a small system in PHP where the user just swipes a badge and presses enter. Somehow I need to make this enter be automatic after a few seconds (the button is already in the focus after filling the field) or that when I pass the badge again (only numbers) the system understands it as an "enter". It's possible?
I'm trying to adapt this function that blocked all letters for this case:
function SomenteNumero(e){
var tecla = (window.event) ? event.keyCode : e.which;
if((tecla > 47 && tecla < 58))
return true;
else{
if (tecla == 8 || tecla == 0)
return true;
else
return false;
}
}
Answer:
I understood your question this way:
How to automate the submission of a form after auto-filling a field?
Monitor the KeyDown and KeyUp events, and after a few seconds of inactivity validate the entered content.
var temporizador; var intervalotemporizador = 2000; //tempo em milissegundos. Neste caso, 2s. var $input = $('#campoCodigo'); //Quando uma tecla for liberada no campoCodigo, iniciar temporizador: $input.on('keyup', function () { clearTimeout(temporizador); temporizador = setTimeout(avaliarConteudoDigitado, intervalotemporizador); }); //Quando uma tecla for pressionada, limpar o temporizador: $input.on('keydown', function () { clearTimeout(temporizador); }); //quando o usuário finalizar a 'digitação': function avaliarConteudoDigitado () { //Faça algo aqui - valide o código, mostre comentários, e ao final submeta o formulário: //document.getElementById("meuForm").submit(); var valor = $input.val(); if (isNaN(valor)) //isNaN: Is Not a Number (verifica se o valor não é numérico) $('#mensagem').val('ERRO: Não numérico.'); else if (valor.length != 10) $('#mensagem').val('ERRO: Número de caracteres diferente de 10.'); else $('#mensagem').val('OK.'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='campoCodigo' /> <input type='text' id='mensagem' />
Adaptado de ‘Run javascript function when user finishes typing instead of on key up?’, SO Original.