-
-
Save MuTLY/f496ad8be8ec7d867d504a9e3533c952 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(); | |
$('#q').selectRange(0, 10); | |
$('#q').selectRange(searchVal.indexOf('{'), (searchVal.indexOf('}')+1)); | |
$.fn.selectRange = function(start, end) { | |
if (!start || !end) { | |
start = 0; | |
end = 9999; | |
} | |
$(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; | |
} else { | |
el.select(); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment