DEV Community

Pandeyashish17
Pandeyashish17

Posted on

Transform Your Input Fields with HTMLInputElement setSelectionRange()

Hello all JavaScript enthusiasts! Are you tired of your users having to manually highlight text in input fields? Fear not, for the HTMLInputElement.setSelectionRange() method is here to save the day!

This handy method allows you to programmatically set the text selection range in an input field. It's as easy as calling the method on an input element and passing in the start and end indices for the selection range.

const input = document.querySelector('input');
input.setSelectionRange(0, 3);  // Highlights the first 4 characters

Enter fullscreen mode Exit fullscreen mode

But wait, there's more! The setSelectionRange() method also accepts an optional third argument, the "selection direction". This allows you to specify whether the selection should be forward (from start to end) or backward (from end to start).

input.setSelectionRange(3, 0, 'backward');  // Highlights the last 4 characters

Enter fullscreen mode Exit fullscreen mode

So go ahead and give your users a break from all that tedious highlighting. With the HTMLInputElement.setSelectionRange() method, you can programmatically highlight text in input fields with ease!

Top comments (0)