I have 3 text boxes for a phone number. As the user types, it automatically moves from one textbox to the next. When the user presses backspace, I can move focus to the pr
<script type="text/javascript">
$(function(){
$('#areaCode,#firstNum,#secNum').keyup(function(e){
if($(this).val().length==$(this).attr('maxlength'))
$(this).next(':input').focus()
})
})
</script>
<body>
<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />-
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />-
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />
</body>
you can set pointer on last position of textbox as per following.
temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();
This is the easy way to do it. If you're going backwards, just add
$("#Prefix").val($("#Prefix").val());
after you set the focus
This is the more proper (cleaner) way:
function SetCaretAtEnd(elem) {
var elemLen = elem.value.length;
// For IE Only
if (document.selection) {
// Set focus
elem.focus();
// Use IE Ranges
var oSel = document.selection.createRange();
// Reset position to 0 & then set at end
oSel.moveStart('character', -elemLen);
oSel.moveStart('character', elemLen);
oSel.moveEnd('character', 0);
oSel.select();
}
else if (elem.selectionStart || elem.selectionStart == '0') {
// Firefox/Chrome
elem.selectionStart = elemLen;
elem.selectionEnd = elemLen;
elem.focus();
} // if
} // SetCaretAtEnd()
I tried lots of different solutions, the only one that worked for me was based on the solution by Chris G on this page (but with a slight modification).
I have turned it into a jQuery plugin for future use for anyone that needs it
(function($){
$.fn.setCursorToTextEnd = function() {
var $initialVal = this.val();
this.val($initialVal);
};
})(jQuery);
example of usage:
$('#myTextbox').setCursorToTextEnd();