Set cursor at a length of 14 onfocus of a textbox
Asked Answered
P

3

8

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

Pedlar answered 8/12, 2009 at 8:41 Comment(1)
I believe it's called caret, not cursor.Sport
L
18

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

Leahy answered 8/12, 2009 at 14:40 Comment(4)
Hai What is node is it textboxIdPedlar
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.Leahy
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);Chorizo
The 'var' before node is redundant since it's already a function parameter. Great function though.Kornegay
T
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

Taishataisho answered 30/10, 2012 at 16:59 Comment(0)
G
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.

Grearson answered 8/12, 2009 at 8:48 Comment(2)
Mark the textbox will be empty is there any solutionPedlar
Yeah, Its for input box and textarea, If yours is Rich Text Box, I am not sure with it then. sorry about that.Grearson

© 2022 - 2024 — McMap. All rights reserved.