开发者

Stop newline submitting a form?

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 f开发者_开发百科orm behaviour if possible!

many thanks!


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();
    }
});


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜