Skip to content

Instantly share code, notes, and snippets.

@cipheos
Forked from beiyuu/select-text-range.js
Last active March 1, 2017 10:20
Show Gist options
  • Select an option

  • Save cipheos/858902496a9785da648c581f1b8da33b to your computer and use it in GitHub Desktop.

Select an option

Save cipheos/858902496a9785da648c581f1b8da33b to your computer and use it in GitHub Desktop.
jQuery:Select a text range (input/textarea)
$.fn.selectRange = function(start, end) {
this.each(function() {
var el = this[0];
if (el) {
el.focus();
if (el.setSelectionRange) {
el.setSelectionRange(start, end);
} else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
} else if (el.selectionStart) {
el.selectionStart = start;
el.selectionEnd = end;
}
}
});
return this;
};
// Useful implementation
$.fn.setCaretPos = function(index) {
this.selectRange(index, index);
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment