1

I have made a <textarea> for inputs. When a user presses 'enter', it automatically takes their input and runs a js function. However apart from running this function, it also takes the cursor to the next line. How do I made it so that the textarea has only one line or pressing enter simply doesn't do anything.

I tried adding the attribute data-role = 'none'. I've even tried adding the CSS file

.textarea{
   resize: none;
}

Nothing seems to be working. What should I try?

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Coolsugar
  • 131
  • 1
  • 2
  • 9
  • 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) – Jax-p Feb 10 '21 at 10:31

3 Answers3

4

I think this is what you looking for, if i understand your question correctly.

let t = document.getElementById("myTxt"); // grab the dom element

t.addEventListener("keydown", (e) => { // once any key is pressed
    if (e.keyCode === 13) { // if the key code is 13 (ENTER)
    e.preventDefault(); // prevent usual browser behavour
  }
});
<div>
  <textarea id="myTxt" cols="15" rows="1" style="resize: none;"></textarea>
</div>
era-net
  • 387
  • 1
  • 11
1
$("textarea").keydown(function(e){
   // Enter was pressed without shift key
   if (e.keyCode == 13 && !e.shiftKey)
   {
       // prevent default behavior
       e.preventDefault();
   }
});

Credit: https://stackoverflow.com/a/18779374/15136568

1

In the js function that handles the event of the textarea you can add: e.preventDefault(); (e is the name of the argument to this function).