Prevent submit on Enter but allow Enter for newLine in TextArea

Viewed 3868

Is it possible to prevent the enter key from submitting forms, but allowing the enter key to work inside input. (E.g. textArea newline)?

I tried so far:

  • e.preventDefault()
  • e.stopPropagation()

Both on the form tag onkeyup="if (e.keyCode == 13))"

This does prevent submission of the form on enter key, but it also prevents the enter key from working inside formfields completely. What I want to achieve is, that when I press the enter key inside a TextArea, that it creates a newLine but when I hit enter in a input type="text"that it doesn't submit the form.

Using JSF 2.3

JQuery solution is also ok.

3 Answers

$(document).keypress(function(e) {
  if(!$(".specialClass").is(":focus")){
    e.preventDefault();
    if(e.which == 13) {
        console.log('You pressed enter!');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
  <textarea name="text" class="specialClass">Text</textarea><br>
  <input type="submit">
</form>

You can test if the element focused is not your textarea like following :

var area = document.getElementById('area');

document.getElementById('doesntSubmit').addEventListener('keydown', function (e) {
  if (e.keyCode === 13 && e.target !== area) {
    e.preventDefault();  
  }
});
<form id="doesntSubmit">
  <input type="text" value="whatever"/>
  <textarea id="area"></textarea>
</form>

Or you could add a data- tag to the elements you don't want to be affected, or a specific class, ... to avoid checking for the tag.

You could also add a css class to the elements which shouldn't submit the form on enter and bind an event handler on it :

$('.doesntSubmit').keydown(function (e) {
  if (e.keyCode === 13) {
    e.preventDefault();  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="doesntSubmit" value="whatever"/>
  <textarea id="area"></textarea>
</form>

try below code:

if(event.keyCode === 13 && event.target.type !== 'textarea') {
            event.preventDefault();
            return false;
        }
Related