Partially select text inside a text field

I want my script to select only part of the text inside the text box ( <input type="text"). How can i do this?

+3
source share
2 answers

You will need to use Range, and multi-browser compatibility is likely to be a problem.

Quirksmode: Creating a Range Object from a Selection Object

If jQuery is an option, here is a function you can use ( link ) ...

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
+2
source

Source: https://habr.com/ru/post/1749055/


All Articles