When sending alerts, cancel the form

I ran into some strange problem when trying to cancel the form submission when I hit the enter key in the text box.

Using the code below, the form is always submitted when a click is entered after closing the alert. If I comment out the warning, the form is no longer submitted for input, then 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 a form to submit without warning? Also any idea why the warning window is causing this problem?

thanks

UPDATE, which is not like IE, affects Firefox and Chrome.

0
source share
2 answers

You return false for the keydown event, not for the submit event. Thus, the submission of the form will continue without change.

Perhaps you can stop the event in the keydown handler, which may be the most elegant solution - I don’t know, maybe someone will come up with a proposal for this.

Meanwhile, as another parameter, you can set the Do Not Submit Form flag in the keydown event, which you then check on the submit form.

Unconfirmed, but should work somewhere in 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 am not 100% OTOH sure whether it is possible to assign properties to these DOM elements ( this.do_not_submit ), but I am sure that it is.

+1
source

Try the following:

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

Source: https://habr.com/ru/post/952637/


All Articles