Radish
Radish

Reputation: 167

Javascript disable form submit on enter but still use it in textareas

How would you stop the enter key from being used to submit a form on a webpage, but still allow the enter key to be used to select an element in a select list or create a new paragraph in a textarea? Or remove the use of the enter key in a textarea also?

Upvotes: 2

Views: 1195

Answers (2)

mayabelle
mayabelle

Reputation: 10014

This should work:

$(document).keypress(function (e) {
  if (e.which == 13 && e.target.nodeName != "TEXTAREA") return false;
});

Upvotes: 3

Radish
Radish

Reputation: 167

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs. Note: commented out is the code that you would use to negate the use of the enter key completely.

<script type="text/javascript">
    function stopRKey(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;} -->
      if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
    }

    document.onkeypress = stopRKey;
</script>

Upvotes: 1

Related Questions