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?
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?
Share Improve this question asked Apr 26, 2012 at 21:42 user6123723user6123723 11.1k19 gold badges72 silver badges111 bronze badges 8- 1 Have you looked at similar questions like this stackoverflow.com/questions/119441/highlight-a-word-with-jquery or that stackoverflow.com/questions/3318229/… ? – nuala Commented Apr 26, 2012 at 21:46
- 2 @yoshi: No, he requested highlighting a text input field. – Bergi Commented Apr 26, 2012 at 22:02
- Tim's answer is good, but only partially correct. The solution he has proposed may be the only "native"-ish solution. However, you can use layered <div> elements to accomplish what you're trying to do. See this jQuery plugin: github.com/garysieling/jquery-highlighttextarea – rinogo Commented Dec 21, 2013 at 0:00
- This is great, but the background text area and the input scroll at different rates in Chrome (but not Firefox) when zoom != 100%. (You can get it to work in Chrome by scaling the shift of the textarea by the zoom, but that would break Firefox.) Is there a cross-browser fix? – ramcdougal Commented Mar 26, 2014 at 14:14
- Thanks for your follow-up! I use this tool on an internal site where we don't have to be concerned about zoom issues (or even cross-browser issues, for that matter). So, I'm afraid I won't be able to help you. However, it is open-source... We welcome any contributions you can make! :) – rinogo Commented Mar 26, 2014 at 18:09
1 Answer
Reset to default 18Within 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.