How to highlight a part part of an Input text field in HTML using Javascript or JQuery

Within a text input box, your only opportunity for highlighting just a part of the text is using the selection. You can do this in all modern browsers with the text box’s selectionStart and selectionEnd properties, or setSelectionRange() method (no idea why both exist).

Live demo: http://jsfiddle.net/YNr7K/

Code:

var input = document.getElementById("textBoxId");
input.value = "Cup of tea";
input.setSelectionRange(0, 3); // Highlights "Cup"
input.focus();

In older versions of IE (< 9), you’ll need to use one of their tiresome TextRanges. See this answer for a function that shows how to do this.

Leave a Comment