Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Part of String inside an Input Box with jQuery

I am trying to figure out how to highlight just some part of text inside an input box using jQuery. It's quite simple to highlight the entire contents of the input box but how do you highlight just one word or couple of letters?

Thanks!

like image 509
Lukasz Avatar asked Jun 21 '10 14:06

Lukasz


1 Answers

For text <input> elements, the following will do the job. The example selects just the word "two" in the input:

function setInputSelection(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        // IE branch
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}

document.getElementById("setSelection").onmousedown = function() {
    var input = document.getElementById("i");
    setInputSelection(input, 4, 7);
    return false;
};
<input id="i" type="text" value="One two three">
<input type="button" value="Set selection" id="setSelection">
like image 118
Tim Down Avatar answered Oct 18 '22 18:10

Tim Down