gadjeel
gadjeel

Reputation: 21

Prevent line break in textarea with JavaScript - how to?

When i click on "enter" I call a function. Within this function I do the following:

  var key = event.keyCode;
  if (key == 13 && !event.shiftKey) 

I am using this function on a textarea.

When I press enter everything works except one thing: A line break is made within the textarea which should be prevented. How to avoid?

Upvotes: 0

Views: 651

Answers (1)

Blackbam
Blackbam

Reputation: 19406

This is how you can do it:

function(event) {  
  event.preventDefault();  
  var key = event.keyCode;
  if (key == 13 && !event.shiftKey) ...
}

event.preventDefault() also works for links and in any other case you want to prevent the default action of an event.

Another important function sometimes is event.stopPropagation().

More information here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

and here: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Upvotes: 1

Related Questions