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
            Asked
            
        
        
            Active
            
        
            Viewed 7,477 times
        
    8
            
            
        - 
                    4I believe it's called caret, not cursor. – Šime Vidas Nov 18 '11 at 21:35
 
3 Answers
20
            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
        nemisj
        
- 11,562
 - 2
 - 25
 - 23
 
- 
                    
 - 
                    node is the DOM instance, but if you need to work with id's, you can add extra "codeline" which will fetch DOM instance for you. – nemisj Dec 09 '09 at 09:07
 - 
                    As DSharma suggested (rolled back the edit, it should have been a comment): In order to make it work for all browsers add timeout to the function call if you want to place the cursor at the beginning of the input text. For Example: `window.setTimeout(function() { setCursor(node,0);}, 1);` – thomaux Jan 10 '14 at 13:25
 - 
                    1The 'var' before node is redundant since it's already a function parameter. Great function though. – Codesmith Mar 27 '14 at 01:22
 
2
            
            
        The moveStart and moveEnd methods expects 2 parameters. The first parameter is a string (character, word, sentence or textedit). The second parameter is an integer and refers to the number of units to move. http://msdn.microsoft.com/en-us/library/ie/ms536623%28v=vs.85%29.aspx
        Erick
        
- 21
 - 1
 
0
            
            
        $("#textbox").selectionStart=14 might works for Firefox, Opera, Chrome, but not sure for IE
PS: There should be length 14 > characters already in textbox to work properly.
        YOU
        
- 120,166
 - 34
 - 186
 - 219
 
- 
                    
 - 
                    Yeah, Its for input box and textarea, If yours is Rich Text Box, I am not sure with it then. sorry about that. – YOU Dec 08 '09 at 09:02