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
Set cursor at a length of 14 onfocus of a textbox
Asked Answered
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
Hai What is node is it textboxId –
Pedlar
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
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
$("#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.
Mark the textbox will be empty is there any solution –
Pedlar
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.