1

I am trying to prevent to submit the form when a user is pressing enter. I am trying to do so in a form that is also using ajax. I want to have the user click on submit after filling out all the necessary stuff and not have them accidentally press enter and have the form submitted.

I have the code below; the alertbox is popping up when pressing 's' for example. also when I press enter I can get a alertbox popping up. But it is not preventing to submit the form.

$("#edit-searchfield").keydown(function(e){
  var code = e.which; // recommended to use e.which, it's normalized across browsers
  if (code == 13) {
    e.preventDefault();
    return false;
  }
  if (code == 83 || code == 13 || code == 188 || code == 186) {
    alert("I am an alert box!");
  }
});
  • You need to disable button on page load and enable it back once form is filed completely – GoodSp33d Mar 31 '13 at 18:53
  • Can you pls provide me with an example on how to do that? – user1973842 Mar 31 '13 at 22:58
  • Something like this perhaps will work for you. jsfiddle.net/daudK/1 – GoodSp33d Apr 1 '13 at 6:10
  • Thanks for the example, but it doesn't prevent me from hitting the enter button . – user1973842 Apr 1 '13 at 12:28
1

And the answer is :-)

$form['#attributes'] = array('onsubmit' => 'return false');

or alternatively (the above will disable submit all together)

  $('#edit-searchfield').keypress(function(event) {
   if (event.keyCode == '13') {
       event.preventDefault();
   }
});
1

Try jQuery's submit() event:

$('#my-form').submit(function(e) {
    if (/* the form is invalid */) {
      e.preventDefault();
    }
});

That's better than adding onsubmit to $form['#attributes']. It's considered bad practice to mix your HTML and JavaScript that way =)

0

Another alternate to achieve that is using the Hide submit button module

Some users accidentally click the submit button more than once while waiting for their post to be saved. In some cases this may result duplicate postings or duplicate e-commerce orders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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