Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda