How to stop selecting text in textBox and set cursor to last when textBox is focusing by TAB keypress in javascript?
I want to stop selecting text in textBox and set cursor to last when textBox is focusing by TAB keypress. how can I do that? please suggest me. I have tried by googling with following code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Document</title>
<script type="text/javascript">
function cursorLast(){
// var no = document.getElementById('get').length;
setCaretPosition(document.getElementById('get'),4);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange){
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</head>
<body>
<form method="get" id="searchform" action="#" >
<input type="text" onblur="if (this.value == '') {this.value = 'test';}" onfocus="if (this.value == 'test') {this.value = '';}" value="test" name="s" />
<br /><br />
<input type="text" value="test" name="s" id开发者_如何学Go="get" onfocus="cursorLast();"/>
</form>
</body>
</html>
This code is not working.
Thanks in advance.
You could do this by capturing the keydown event of the first input and then preventing the default tab behaviour.
<head>
<script type="text/javascript">
function KeyDownHandler(event)
{
var e = event.which || event.keyCode;
if (e == 9)
{
event.preventDefault();
setCaretPosition(document.getElementById('get'), 4);
}
}
function setCaretPosition(ctrl, pos)
{
if (ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange)
{
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</head>
<body>
<form>
<input type="text" value="test" name="s" onkeydown="KeyDownHandler(event);" />
<br /><br />
<input type="text" value="test" name="s" id="get" />
</form>
</body>
Another tricky solution.
<head>
<script type="text/javascript">
function setCursorLast(elem){
var elemId = elem.id;
var pos = $(elem).attr("value").toString().length;
setTimeout(function(){setCaretPosition(document.getElementById(elemId), pos)}, 1);
}
function setCaretPosition(ctrl, pos){
if (ctrl.setSelectionRange){ // for FF
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange){ // for IE
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</head>
<body>
<form>
<input type="text" value="test" name="s" />
<br /><br />
<input type="text" value="test" name="s" id="get" onfocus="seCursorLast(this)"/>
</form>
</body>
精彩评论