šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Select text or set the cursor in a HTML input with Javascript

Tip of the day: for any HTML Input Element, we have access to a setSelectionRange() method that controls where the cursor is placed in that element, and also what text is selected.

The setSelectionRange() takes a starting position parameter and the ending position. Both are zero indexed.

For example:

input.focus()
// select the first 6 chars from the input
input.setSelectionRange(0, 6)

Note that in order to see the setSelectionRange() working, you first need to focus the input element!

If these 2 parameters are equal then it will just place the cursor/caret at that position:

//move the cursor to a specific index 
input.setSelectionRange(2, 2)

// move the cursor at the end of an input
const {length} = inputElement.value
inputElement.setSelectionRange(length, length)

So, it's very easy to select and change just some parts of the text from a html input:
Programmatically select text or set the cursor in a HTML input

The below Javascript code does this:

const input = document.getElementById("my-input")

function renameFile() {
  input.focus()
  const dotIndex = input.value.lastIndexOf('.')
  input.setSelectionRange(0, dotIndex)
}

function changeFileExtension() {
  input.focus()
  const {value} = input
  const dotIndex = value.lastIndexOf('.')
  input.setSelectionRange(dotIndex + 1, value.length)
}

You can see here the full working codepen here.

By the way, speaking of cursor/caret in an HTML input you can also set its color with the CSS caret-color property.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *