Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cursor at a length of 14 onfocus of a textbox

Hai Guys, I want to set cursor at a position of length 14 on a textbox which will not have a value.. Iknow initially cursor will be at 0 i want it to be at 14

like image 369
ACP Avatar asked Dec 08 '09 08:12

ACP


1 Answers

IE use different approach at setting cursor position than Firefox,Opera and Chrome. It's better to make a helper function, which will do it for you. I use this one for own needs.

function setCursor(node,pos){

    node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if(!node){
        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        return true;
    }

    return false;
}

Last thing, is to call it from your onfocus handler.

Goodluck

like image 199
nemisj Avatar answered Oct 08 '22 22:10

nemisj