JQuery/JavaScript - Highlight A Part Of Text From Input Or Textarea
Possible Duplicate: How to highlight a part part of an Input text field in HTML using Javascript or JQuery Does anyone know how to highlight some text in input[type=text] or tex
Solution 1:
You have to place a div
behind your textarea
and then style it according to it's text.
Notes:
- Set your
textarea
background-color
to transparent to see yourhighlighter
color. - Your
highlighter
have to be the same style and text content of yourtextarea
to put thespan
on the right place. - Set your
highlighter
text to the same color of it's background or you'll see a<b>
effect, the same for thespan
.
html:
<div class="highlighter">some text <span>highlighted</span> some text</div>
<textarea>some text highlighted some text</textarea>
css:
.highlighter, textarea {
width: 400px;
height: 300px;
font-size: 10pt;
font-family: 'verdana';
}
.highlighter {
position: absolute;
padding: 1px;
margin-left: 1px;
color: white;
}
.highlighter span {
background: red;
color: red;
}
textarea {
position: relative;
background-color: transparent;
}
Solution 2:
This code snippet shows you how:
window.onload = function() {
var message = document.getElementById('message');
// Select a portion of text
createSelection(message, 0, 5);
// get the selected portion of text
var selectedText = message.value.substring(message.selectionStart, message.selectionEnd);
alert(selectedText);
};
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
}
Post a Comment for "JQuery/JavaScript - Highlight A Part Of Text From Input Or Textarea"