Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  18] [ 2]  / answers: 1 / hits: 18431  / 12 Years ago, thu, april 26, 2012, 12:00:00

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?


More From » jquery

 Answers
12

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.


[#85942] Thursday, April 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
citlalia

Total Points: 138
Total Questions: 104
Total Answers: 87

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;