Skip to content Skip to sidebar Skip to footer

Cancel Form Submit When Showing Alerts

I've come up against a weird problem when trying to cancel a form submit when the enter key is pressed in a text box. Using the code below the form always submits when enter is pre

Solution 1:

You are returning false for the keydown event, not for the submit event. This way, form submission will go ahead unchanged.

It may be possible to stop the event in the keydown handler which might be the most elegant solution - I don't know, maybe somebody comes up with a suggestion for that.

Meanwhile, as another option, you could set a "do not submit form" flag in the keydown event that you then check for in the form's submit event.

Untested but should work somewhere along these lines:

  // in the `keydown` function
  if (key == 13) {
    alert('Test text.'); 
    this.form.do_not_submit = true;

......

<form onsubmit="submit()"...>
....

function submit()
 {
   if (this.do_not_submit == true) 
     return false;

 }

I'm not 100% sure OTOH whether it's possible to assign properties to DOM elements like that (this.do_not_submit) but I'm pretty sure it is.


Solution 2:

Try this:

if (key == 13) {
    alert('Test text.');

    // if preventDefault exists run it
    if (event.preventDefault) {
        event.preventDefault();
    }
    // otherwise set the returnValue property of the event to false (IE)
    event.returnValue = false;

    return false;
}

Post a Comment for "Cancel Form Submit When Showing Alerts"