Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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.
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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}

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!