Trapping return for form field focus
21 Feb 2006Today I had to cook up a simple form with two input fields, so that two barcodes could be scanned into their respective fields and then submitted (the point being to link two IDs in a database that have been encoded in separate barcodes). There was one twist.
The barcode reader automatically appends a return character to the end of the string it’s read… which would, in any normal circumstance, submit the form. Obviously problematic unless we split the form over several pages, which is just yuck.
If the barcode reader hadn’t returned character 13 (return/enter/whatever you’ll call it) at the end of the string, it’d be trivial to pick up a “maxlength=x then go to next field” script off the side of the road… they’re everywhere. Not so much the case with this exact problem, though, so I thought I’d share…
[source:str javascript]function catchEnter(e){
var characterCode
if(e && e.which){
e = e
characterCode = e.which
} else {
e = event
characterCode = e.keyCode
}
if(characterCode == 13){
document.getElementById(‘cardid’).focus();
return false
} else{
return true
}
}[/script]
Note we’re not using DOM methods here… there isn’t any equivalent to which
or keyCode
that I’m aware of (I looked enough). keycode
is the important one… which
is used by the likes of Netscape 4.x and other nasties… I don’t really want to know about it, but I stole the key trap code from somewhere (lost the site) and didn’t really have a reason to intentionally break the behaviour for those browsers!
So we use one of those (probably keycode) to set characterCode, which is a numeric value that corresponds to Unicode decimal values. 13 is carriage return. Then it needs to be compared to event
(the character that triggered the onkeypress event), here used as e
for convenience… and if this is true, then focus will go to the next field (in this case cardid
) and the character will return false
to prevent the form from submitting.
I’ve got a static demo here (don’t mind the message at the top, it was an HTML mockup)… try entering something into the first field and pressing return. Then press return again, and the form will submit.
Obviously this Javascript only works for a two-field case… but you could dynamically set the element for focus to follow to by parsing that through to the function onkeypress
event. The only other thing I can think of is to getElementsByTagName every input field in the form and use the array to dynamically set the “next” field… but that would have been waaaay overkill for what I had to do.
This behaviour isn’t just useful for barcode scanners, by the way. Desktop applications often exhibit this kind of behaviour, and it also goes some way to ensuring all fields are filled without doing formal validation (either JavaScript on submit
, or server-side).