Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  139] [ 3]  / answers: 1 / hits: 16525  / 8 Years ago, tue, may 10, 2016, 12:00:00

I need to archieve 2 objectives but I archive one at time, never both of them.
First I have an input field that should fires an event when a key is pressed and I need to catch the field value. I use letters, number and the TAB key. So if I use keyup it fires at the first char. If I use keydown it takes 2 char to fire because when it fires the first time the char is not pressed yet. So when I press for the second time it fires with the first letter and so on.



Said that, it is clear that what I need is the keyup event that put the value in the field then the event is fired. But TAB has a special meaning in my case and it is not the default behavior and with TAB key I am unable to catch e.which, e.charCode nor e.keyCode! Only with keydown I am able to get those value!



Now I don´t have a clue what to do. How could I catch TAB key or make keydown catch the value of a field?



P.S keypress also working as keydown. Event is fired before I have the value in the field



EDIT 1:
Here is the code:



$('input[data-action=keyupNome]').each(function () {          
$(this).on(keypress, function(e) {

//Se o campo não estiver vazio
if($(this).val() != '') {

if(key != 9) // the tab key code
{
limpaCamposBusca('nome');

var width = $('#nomeBusca').width();
$('.nomeContainer').css('width', width);
$('.displayNomeTbl').css('width', width);

buscaEndereco('Controller/Dispatcher.php?classe=Buscas&acao=buscaEnderecoPorNome', 'nome');

}//if key == 9
else {
alert('here');
e.preventDefault();
}
}// val == ''
else {
clearFields();
clearBuscaCliente();
reactivateFields();
}

});
});

More From » jquery

 Answers
23

The trick is to use keydown and to combine actual value of the field with the char currently pressed OR to catch TAB in keydown and set an external variable to be used in keyup as in my example.



EDIT :
In fact, I realized that not preventing default behavior of TAB in keydown doesn't fire keyup. So, no variable is needed, but only preventing TAB on keydown. Anyhow, this version always work if the glitch you talked about exist in some circumstances.





(function() {

var tabKeyPressed = false;

$(#t).keydown(function(e) {
tabKeyPressed = e.keyCode == 9;
if (tabKeyPressed) {
e.preventDefault();
return;
}
});

$(#t).keyup(function(e) {
if (tabKeyPressed) {
$(this).val(TAB); // Do stuff for TAB
e.preventDefault();
return;
}

//Do other stuff when not TAB
});

})();

<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<input id=t value=>




[#62231] Monday, May 9, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emileef

Total Points: 724
Total Questions: 108
Total Answers: 102

Location: Romania
Member since Sun, Dec 20, 2020
4 Years ago
;