Skip to content

Instantly share code, notes, and snippets.

@noneorone
Created March 21, 2012 08:46

Revisions

  1. noneorone created this gist Mar 21, 2012.
    34 changes: 34 additions & 0 deletions selectText
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    /**
    * 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();
    }