Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
user6123723 Avatar asked Apr 26 '12 21:04

user6123723


People also ask

How do you highlight text in HTML input?

For selecting the content of an input (with highlight), use: el. select() .

How do you highlight text in Javascript?

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.

How do you access the inner content of a text input field?

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.

How do you highlight text in search?

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.


1 Answers

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.

like image 106
Tim Down Avatar answered Oct 04 '22 00:10

Tim Down