Artemis
Artemis

Reputation: 599

Replace character in textfield on keydown

I have a textarea, when I press Enter I need to insert a custom {br} tag instead of wrap the text on a new line. I have solved the wrap issue with CSS, the problem is that when I press enter the tag is inserted at the end of the string. How can I insert it in the same position of the input?

HTML

<textarea class="form-control d-inline-block ml-3 my-auto" rows="1" value="" onkeydown="tagOnInput(this, window.event.keyCode)"></textarea>

CSS

textarea[rows="1"] {
    overflow: auto;
    white-space: nowrap;
}

JS

function tagOnInput(textField, key){
  if (key === 13) {
      textField.value = textField.value + "{br}"; // Tag is added at the end, but should be in the cursor position.
  }
}

Upvotes: 1

Views: 1256

Answers (2)

thchp
thchp

Reputation: 2384

You can use textField.selectionStart and textField.selectionEnd to get the cursor position. Then use substring() to extract the two parts of the String, and concatenate the two with {br} in between

const el = document.getElementById("area")
const btn = document.getElementById("btn")

area.addEventListener('keydown', (e) => {
  if (e.which === 13) {
    e.preventDefault()
    const selectionStart = el.selectionStart
    const selectionEnd = el.selectionEnd
    const value = el.value
    const toInsert = '{br}'

    const partLeft = value.substr(0, selectionStart)
    const partRight = value.substr(selectionEnd)

    el.value = partLeft + toInsert + partRight
    el.focus()
    el.selectionEnd = selectionEnd + toInsert.length
    el.selectionStart = selectionEnd + toInsert.length
  }
  
})
<label>Textarea</label>
<textarea id="area"></textarea>

If the is not selecting text, this will insert at the cursor position. If he is, this will replace the selected text by {br}

Upvotes: 2

johnnyBoy
johnnyBoy

Reputation: 125

You currently append your tag after the textField's value. Whatever is in your textField it'll always add it at the end.

You have to get your cursor's position, and insert your tag at this position in your textField's value, maybe using something like javascript slice I guess.

get cursor position in a textarea

Upvotes: 1

Related Questions