Skip to content

Instantly share code, notes, and snippets.

@noneorone
Created March 21, 2012 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noneorone/2145655 to your computer and use it in GitHub Desktop.
Save noneorone/2145655 to your computer and use it in GitHub Desktop.
To choose the specific characters of the content which included in the specific component.
/**
* To choose the specific characters of the content which included in the specific component.
* @param {String} tagName: the name of a tag(eg.textarea,input etc.)
* @param {Object} obj: component
* @param {Integer} begin: the start index
* @param {Integer} end: the end index.
* @author wangmeng
* @date 2011-10-10
*/
function selectText(tagName, obj, begin, end){
if(document.selection){
if(obj.tagName == tagName){
var i = obj.value.indexOf("\r", 0);
while(i != -1 && i < end){
end--;
if(i < begin){
begin --;
}
i = obj.value.indexOf("\r", i+1);
}
}
var range = obj.createTextRange();
range.collapse(true);
range.moveStart('character', begin);
if(end != undefined){
range.moveEnd('character', end-begin);
}
range.select();
}else{
obj.selectionStart = begin;
var sel_end = (end == undefined) ? begin : end;
obj.selectionEnd = Math.min(sel_end, obj.value.length);
obj.focus();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment