0

I need Enter key to be active for textarea only on my HTML form. My Javascript/jQuery code looks like this for now:

$('#formId').on('keyup keypress', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
//if this is textarea return true;
    e.preventDefault();
    return false;
}
});

I need to check if focus on textarea inside this form and allow user to press enter.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Sam Alekseev
  • 2,281
  • 2
  • 19
  • 28
  • And what's your question about this? – Nico Haase Nov 03 '20 at 15:23
  • Does https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event help you? – Nico Haase Nov 03 '20 at 15:23
  • Does this answer your question? [How to prevent ENTER keypress to submit a web form?](https://stackoverflow.com/questions/585396/how-to-prevent-enter-keypress-to-submit-a-web-form) – kmoser Nov 03 '20 at 15:45

1 Answers1

3

I would use the keydown event because it is fired first.

You just have to add an additionnal comparison to check the tagName of the element where the event fired.

$('#formId').on('keydown', function(e) {
  var keyCode = e.keyCode || e.which;
  var tag = e.target.tagName
  if (keyCode === 13 && tag !=="TEXTAREA") {
    console.log("Enter prevented")
    e.preventDefault();
    return false;
  }else{
    console.log("Enter is ok...")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formId">
<input type="text" value="ENTER does not work here"/><br>
<textArea>ENTER works here</textarea>
</form>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64