5

I have a slightly unusual form-related problem. My web app listens for scanner input from a barcode reader. The barcode reader presents as keyboard input in the following format:

~100.0101~\n

where \n is a newline. I use a global javascript listener with a regex - whenever the listener 'hears' input that matches the regex, I call my barcodeHandler() function.

Unfortunately, this doesn't interact well with forms: if the user is focussed on a form input when they scan, the form is submitted and posts back before the listener kicks in, because the form takes \n to mean 'submit'.

I can't change the scanner input, so is there any way I can stop the forms submitting when the \n is entered?

Obviously, I'd still like my forms to work with the Enter key, and I'd rather not change the default form behaviour if possible!

many thanks!

4
  • 1
    you can use jquery and assign a special function on key actions and do event.preventdefault(); to prevent the "enter" key from being processed as a submit of the form.
    – ITroubs
    Apr 4, 2011 at 12:49
  • Thanks - though I'd really like the Enter key still to work - just not the \n supplied by the barcode scanner. Is there a way to distinguish between the two?
    – AP257
    Apr 4, 2011 at 13:03
  • Ah, I can just apply the event listener when the first part of the regex has been matched. That works.
    – AP257
    Apr 4, 2011 at 13:24
  • FYI: a < textarea > will not submit forms with the newline ( \n ) from a barcode readers input.
    – user891901
    Aug 12, 2011 at 14:00

2 Answers 2

10

You need to capture the keypress on form controls and prevent the default action using preventDefault() or return false.

// do this for all <input> <textarea> and <select> elements on the page.
input.addEventListener("keypress", function(event){
    if (event.which == '10' || event.which == '13') {
        event.preventDefault();
    }
}, false);

or using jQuery:

$("input, textarea, select").keypress(function(event){
    if (event.which == '10' || event.which == '13') {
        event.preventDefault();
    }
});
1
  • 1
    works like a charm! I used like this: $(":input").keypress( //code ) because i wanted to capture this on all inputs. thanks. +1 Oct 26, 2011 at 22:17
3

Override the form's onsubmit and supply your own alternative as an onclick handler on the submit button.

<form action="submit.php" onsubmit="return false;">
    Some input ...<input type="text"/>
    <input type="button" value="Submit" onclick="parentNode.submit();">
</form>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.