sexta-feira, setembro 14, 2007

Javascript: Send Tab key on Enter.

I just finished doing some dirty work in javascript, and it's some interesting stuff.

The problem was with a software I wrote in PHP for the previous company I used to work, a user bought a bar code reader and wanted to use it with the software, but the stupid bar code reader sends an "Enter" key after it reads the bar code, so the software submited the form and the user got really pissed.

Anyway, the solution was this piece of code:
function getIndex(input)
{
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}

function SendTab(objForm, , strField, evtKeyPress)
{
var aKey = evtKeyPress.keyCode ?
evtKeyPress.keyCode :evtKeyPress.which ?
evtKeyPress.which : evtKeyPress.charCode;

if (aKey == 13)
{
objForm[(getIndex(objForm[strField])+1) % objForm.length].focus();
}
}

I found most part of this solution on google and just adapted it to my needs, sorry about not giving the credits to the author, but I got pieces of code from a lot of places and can't find them again, if you are the author of some of this code, please let me know.

To use it, just put this on your input code:

onkeypress="return SendTab(document.forms['f'], 'yourfieldname', event);"

It will process the "Enter" key as a Tab and go to the next input.

Um comentário:

scragar disse...

you do realise that the

found = false

part of that first function is completely worthless right? You create the variable and assign a value, but you never actualy use it :P.