Skip to content

Instantly share code, notes, and snippets.

@beiyuu
Last active September 23, 2022 19:52
Show Gist options
  • Save beiyuu/2029907 to your computer and use it in GitHub Desktop.
Save beiyuu/2029907 to your computer and use it in GitHub Desktop.
jQuery:Select a text range (input/textarea)
//USE CASE
$('#q').selectRange(0, 10);
$('#q').selectRange(searchVal.indexOf('{'), (searchVal.indexOf('}')+1));
//Source here : http://plugins.jquery.com/project/selectRange
$.fn.selectRange = function(start, end) {
var e = document.getElementById($(this).attr('id')); // I don't know why... but $(this) don't want to work today :-/
if (!e) return;
else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */
else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
};
@cipheos
Copy link

cipheos commented Mar 1, 2017

Also, super useful:

$.fn.setCaretPos = function(index) {
    $(this).selectRange(index, index);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment