Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable form submit with enter key?

Tags:

javascript

I have a js event on enter keypress which works fine. But after that event it also submits the form which has a submit button. How do I stop that submit button from getting focus after the previous keypress event?

EDIT: I DONT WANT THE SUBMIT BUTTON TO SUBMIT ON ENTER, ONLY ON CLICK.

like image 854
zsharp Avatar asked Apr 30 '10 18:04

zsharp


3 Answers

You can do this with java script are as follows;

    <script type="text/javascript">

    function stopReloadKey(evt) {
      var evt = (evt) ? evt : ((event) ? event : null);
      var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
      if (evt.keyCode == 13)  {
          return false;
      }
    }

    document.onkeypress = stopReloadKey;

    </script> 

Or Using Jquery you can do this by,

<script type="text/javascript">
        $(document).ready(function() {
           $("form").bind("keypress", function(e) {
              if (e.keyCode == 13) {
                 return false;
              }
           });
        });
</script>
like image 72
Kailas Mane Avatar answered Nov 03 '22 11:11

Kailas Mane


Not sure if I understand correctly, but if you are trying to prevent the form from getting submitted:

Attach an onsubmit event and return false from it.

<form onsubmit="submit_handler();"></form>
[...]

function submit_handler()
{
    //do stuff
    return (false);
}
like image 26
nc3b Avatar answered Nov 03 '22 11:11

nc3b


Typically the answer to javascript questions of the type "How do I keep my form from submitting after I ...." is "make your javascript function return false".

like image 41
Jacob Mattison Avatar answered Nov 03 '22 11:11

Jacob Mattison