Jon Lamer
Jon Lamer

Reputation: 438

Why does my form reload the page?

I prefer submitting form values with AJAX by hitting "Return" and all my setups, which I did before, are working, but today it stopped working. Here are the the steps, which I have been following for a quite a long time.

  1. Include jQuery
  2. Setup my form
  3. Preventing it form submitting
$(document).ready(function(){
  $(document).on('keyup', myFormSelector, function(event){
    if ( event.keyCode === 13 ) {
      event.preventDefault();
    }
  });
});

Upvotes: 0

Views: 134

Answers (2)

rulebot
rulebot

Reputation: 232

try to disable the default behaviour from the submit event and add a SUBMIT-element (display:none).

If a form does have a submit-element, the return key does work like you want it.

Howto disable the submit event:

$('#myForm').submit(function(e) {
    e.preventDefault(); // disabling default submit with reload.
    // ajax code here
});

if this does not work, u may try this also:

<form id="myForm" onsubmit="return false"> ... </form>

Returning false does stop submitting too.

When using submit elements instead of keyup/keydown, you will be able to add multiple forms on your page with the desired behaviour.

Upvotes: 1

Nouphal.M
Nouphal.M

Reputation: 6344

change the event to keydown and it will work.

Upvotes: 2

Related Questions