Reputation: 192
I have a textarea that I want users be able to input text in. Each new line within the textarea will eventually get split up and sent back to the database to be used elsewhere. To show this from a users perspective, I want to add a bullet to each new line that they enter within the textarea.
I've got this working to the point where it successfully adds a bullet when you press enter and are on the last line of the textarea content
<textarea onInput="handleInput(event)" rows="10"></textarea>
let previousLength = 0;
const handleInput = (event) => {
const bullet = "\u2022";
const newLength = event.target.value.length;
const characterCode = event.target.value.substr(-1).charCodeAt(0);
if (newLength > previousLength) {
if (characterCode === 10) {
event.target.value = `${event.target.value}${bullet} `;
} else if (newLength === 1) {
event.target.value = `${bullet} ${event.target.value}`;
}
}
previousLength = newLength;
}
https://codepen.io/andrewgarrison/pen/vqqmMv?editors=1010
However, I'd also like for it to add a bullet when you are in the middle of the textarea content and you press enter. Right now it just adds a new line with no bullet.
Upvotes: 3
Views: 5771
Reputation: 111
For anyone else who come accross this problem, here is how I did it:
.text-area {
display: list-item;
margin-left : 1em;
outline: none;
}
.text-area div {
display: list-item;
}
<div class="text-area" contenteditable="true">
</div>
Upvotes: 3
Reputation: 6466
You can find the current position within the text area, and when enter is pressed, append a new line and a bullet:
const bullet = "\u2022";
const bulletWithSpace = `${bullet} `;
const enter = 13;
const handleInput = (event) => {
const { keyCode, target } = event;
const { selectionStart, value } = target;
if (keyCode === enter) {
console.log('a');
target.value = [...value]
.map((c, i) => i === selectionStart - 1
? `\n${bulletWithSpace}`
: c
)
.join('');
console.log(target.value);
target.selectionStart = selectionStart+bulletWithSpace.length;
target.selectionEnd = selectionStart+bulletWithSpace.length;
}
if (value[0] !== bullet) {
target.value = `${bulletWithSpace}${value}`;
}
}
<textarea onkeyup="handleInput(event)" rows="10"></textarea>
Upvotes: 10