简体   繁体   中英

Wrappable one-line text input

I am writing an browser-based text editor for one of my projects. Each text has a title, which the user can edit. The user should not be able to format that title or add any html to it, it should just be a plain string.

A <input type="text"> element would be ideal, but since titles can be very long I need line wrapping, which is something that the input tag cannot do, as far as I know.

I could use a <textarea> , but that would allow the user to add line breaks manually, which I don't want.

I could use <p contenteditable="true"> , but that can add unwanted markup and the user would be able to insert manual line breaks and other markup.

I could write a whole bunch of JavaScript to validate and restrict a <textarea> or contenteditable tag, but that seems to be very error-prone and could introduce cross-browser inconsistencies. Or am I making this way too complex and there is an easy way to prevent misuse?

I'm sure people have solved this problem before. What am I missing here? Do I really need a massively complex JavaScript solution to have a wrappable one-line text input?

Incidentally, I'm using tiptap as my editor component. I know that it can do title inputs but so far I haven't figured out how to extract that title. I want it to be stored separate from the text, not as part of the text. If anybody has inputs regarding using tiptap to solve my problem, that would also qualify as an answer - although I think it's a bit overkill to use a full-fledged richtext editor for a simple, unformatted one-liner. I would prefer more lightweight solutions.

Here are two simple solutions :

Disable Enter key on client side

 document.querySelector('#textInput').addEventListener('keydown', function(event) { var keyCode = event.keyCode || event.which; // If ENTER key if (keyCode === 13) { event.preventDefault(); // do nothing } } );
 <html> <body> <textarea id="textInput" rows=3></textarea> </body> </html>

Remove line breaks on server side

let text = inputText.replace(/\n/, '');

Demo

Or replace them with a space then replace double spaces with one

let text = inputText.replace(/(\r\n|\n|\r)/gm, ' ').replace(/\s+/g, ' ');

Demo

Using both solutions is better than only one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM