uhsarp uhsarp - 1 year ago 77
jQuery Question

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

I'm performing some form of validation on a freely typed input text field in HTML. Is there a way to highlight certain words or phrases (based on certain criteria) in a input text field using JQuery or JavaScript?

Answer Source

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/


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

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.