How to highlight a part part of an Input text field in HTML using Javascript or JQuery
html, javascript, jquery, validation
Solution
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.
Problem
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?