Prevent line breaks in text area fields

Prevent line breaks in text area fields

So I came across an occasion where I needed to use ‘TextArea’ fields to allow for more that one line of text, but wanted to prevent users from typing in line breaks or returns manually. So the question arose how do I prevent line breaks in text area fields but allow text to naturally break down to the next line.

After a few attempts I have found away that allows a multi line text area to be used but blocks the user from using ‘enter/return’ or ‘shift and ‘enter/return’. Manual line breaks were breaking a behind the scenes script and causing it to become slightly unpredictable. By using this fix it allows a user to enter the amount of text they require but takes the line breaks/returns out of their hands and lets the software detail with it.

Prevent line breaks in text area fields -Example

Html

<textarea contenteditable="true">
Sample text here.
</textarea>

JavaScript

 $('[contenteditable]').on('keypress', function(e){
    	 return e.which != 13;
    }); $('[contenteditable]').on('keypress', function(e){
    	 return e.which != 13;
    });

Try it in the live code editorJSFiddle

Please feel free to use. If you find it useful please comment below.

About the author

James Harding administrator

Leave a Reply

%d bloggers like this: