billc.cn
billc.cn

Reputation: 7317

How to prevent form submission using the keyboard (esp. the space key)

I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.

I have written this code:

$('button').keydown(function (e) {
    if (e.which === 10 || e.which === 13 || e.which === 32) {
        return false;
    }
});

However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?

Edit:

Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.

Edit 2:

I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.

Upvotes: 2

Views: 3146

Answers (3)

aagjalpankaj
aagjalpankaj

Reputation: 1180

Use below code. 13 for Enter key and 32 for Spacebar.

$("#form_id").on('keydown keyup keypress', function( e ) {

    if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
        e.preventDefault();
        return false;
    }
});

Upvotes: 0

billc.cn
billc.cn

Reputation: 7317

Just found out: handling space (32) on keyup will prevent the click event.

Updated fiddle: http://jsfiddle.net/3JmtY/2/

Upvotes: 1

Stefan
Stefan

Reputation: 14863

Missed the Point of your Question. After some googleing if found the following trick:

Bind the keypress event to your from and listen to it's keycode. If the keycode is 13 (enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).

Her is a fiddler code example:

HTML:

<form id="target" action="destination.html">
    <input type="text" value="Hello there" />
    <input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>

JavaScript:

$('#target').keypress(function (event) {
    var code = event.keyCode || event.which; 
  if (code  == 13) {               
    event.preventDefault();
    return false;
  }
});

$('#target').submit(function (event, data2) {
    debugger;
    alert('test');
    return false;
});

Fiddler: http://jsfiddle.net/ggTDs/

Note that the form is not submited when enter is clicked!

Upvotes: 0

Related Questions