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?
For selecting the content of an input (with highlight), use: el. select() .
js code to highlight the text. There are many built-in functions in mark. js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before.
Answer: Use the value Property You can simply use the value property of the DOM input element to get the value of text input field.
Use the "Highlight Text by Search" dialog to configure the text search and highlighting options. The input document will be searched for text listed in the 'Highlight Words' entry box.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With