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 TextRange
s. See this answer for a function that shows how to do this.