3

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.

Chiff Shinz
  • 377
  • 2
  • 14
  • 2
    Without the code, it will be difficult to help you out but I suspect you bind the event listener to the form as you only have to bind it to the inputs you want to actually listen – 3Dos Nov 13 '17 at 13:54
  • @3Dos yes I bind the event listener to the whole form. Otherwise I would have to add a listener to every `input` tag individually which I would not like to do. – Chiff Shinz Nov 13 '17 at 13:59

3 Answers3

6

Get keypress event then check if specialClass is not :focus and check the pressed key (13 = Enter key)

$(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>
SKJ
  • 2,184
  • 1
  • 13
  • 25
3

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>
Serge K.
  • 5,303
  • 1
  • 20
  • 27
-1

try below code:

if(event.keyCode === 13 && event.target.type !== 'textarea') {
            event.preventDefault();
            return false;
        }
Sumon Bappi
  • 1,937
  • 8
  • 38
  • 82