zohair
zohair

Reputation: 2369

Highlighting text in a textbox using Javascript

I have an ASP.NET 2.0 webapp (with C#). I wanted to add a button which, when clicked would highlight selected text. By 'highlight', I mean change the CSS properties of the text so that it can stand out. I think this can be done with some clientside JavaScript.

I know that you can assign a Javascript function to the onclick event of an HTML input button, but since I'm not very proficient at JS the function itself I have no idea how to write...

Can someone please help?

Thanks a bunch!

Upvotes: 1

Views: 3170

Answers (3)

Abe Miessler
Abe Miessler

Reputation: 85056

Looks like there is a jQuery plugin that does something similar to what you want. Not sure if it works inside of a textbox but it probably wouldn't take much to get it there. Check out this link: http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

Upvotes: 1

Zlatko
Zlatko

Reputation: 19569

It would be something like this:

The function:

< script type="text/javascript">

function highlightMyText() {

elem=document.getElementById('textToTurnRed');

elem.style.color="red";

}

< /script>

Then in the body:

< div id="textToTurnRed">

My text that will be turned red < /div>

Then the button:

< input type="button" value="Turn Red" onclick="highlightMyText" />

You can do all sorts of stuff with element.style, like change the color, visibility, whatever you need.

Upvotes: 0

Eugeniu Torica
Eugeniu Torica

Reputation: 7574

It seemns to me that be best solution is to use regex to find searched text and then wrap it in a tag which has certain desired style assigned to it.

You could look here at w3schools or briefly

var searchString = "abra";
string.replace(searchString,"<span class='highlight'>"+searchString+"</span>")

Upvotes: 0

Related Questions