Last active
September 23, 2022 19:52
-
-
Save beiyuu/2029907 to your computer and use it in GitHub Desktop.
jQuery:Select a text range (input/textarea)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; } | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, super useful: