Skip to content Skip to sidebar Skip to footer

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 textareabackground-color to transparent to see your highlighter color.
  • Your highlighter have to be the same style and text content of your textarea to put the span 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 the span.

html:

<divclass="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;
}

.highlighterspan {
    background: red;
    color: red;
}

textarea {
    position: relative;
    background-color: transparent;
}

demo

Solution 2:

This code snippet shows you how:

window.onload = function() {
    var message = document.getElementById('message');
    // Select a portion of textcreateSelection(message, 0, 5);

    // get the selected portion of textvar selectedText = message.value.substring(message.selectionStart, message.selectionEnd);
    alert(selectedText);
};

functioncreateSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end);
        selRange.select();
    } elseif( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } elseif( 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"