šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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