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; } | |
}; |
var e = $(this)[0]; // The original DOMelement.
or this[0]
Here it is converted into coffeescript...
$.fn.selectRange = (start, end) ->
e = this[0]
return unless e
if e.setSelectionRange # WebKit
e.focus()
e.setSelectionRange start, end
else if e.createTextRange # IE
range = e.createTextRange()
range.collapse true
range.moveEnd 'character', end
range.moveStart 'character', start
range.select()
else if e.selectionStart
e.selectionStart = start
e.selectionEnd = end
$.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;
}
}
});
};
Please note that a jQuery function receives a collection of jQuery objects. That is why "$(this) didn't want to work that day :-/". Of course performing this on a collection of input elements, would result in only the last element actually having a selection. It works as expected.
To make this extension behave the same in every browser, I changed it to always focus the input (not just for webkit).
I've expanded the code to make it readable, it wasn't really minified anyway...
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
Try it with
var e = document.querySelector($(this).selector);
, should work also on different selector than id, likeetc.