Magpie
Magpie

Reputation: 7173

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 pressed after I close the alert. If I comment out the alert the form no longer submits on enter, the desired result.

<input id="myTextBox" type="text" onkeydown="return myFunction(event);">

function SearchOnEnter(event) {
    var key = event.charCode || event.keyCode || e.which || 0;

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

        return false;
    }
    else
        return true;
}

Is there a way to get the form not to submit after showing the alert? Also any idea why the alert box is causing this problem?

Thanks

UPDATE, this doesn't seem to be an issue on IE, affects Firefox and chrome.

Upvotes: 0

Views: 1194

Answers (2)

Soe Moe
Soe Moe

Reputation: 3438

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

Upvotes: 0

Pekka
Pekka

Reputation: 449415

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.

Upvotes: 1

Related Questions