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
You should code like this.
var num = $('#Number').val();
$('#Number').focus().val('').val(num);
Code for any Browser:
function focusCampo(id){
var inputField = document.getElementById(id);
if (inputField != null && inputField.value.length != 0){
if (inputField.createTextRange){
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}else if (inputField.selectionStart || inputField.selectionStart == '0') {
var elemLen = inputField.value.length;
inputField.selectionStart = elemLen;
inputField.selectionEnd = elemLen;
inputField.focus();
}
}else{
inputField.focus();
}
}
var val =$("#inputname").val();
$("#inputname").removeAttr('value').attr('value', val).focus();
// I think this is beter for all browsers...
This works fine for me . [Ref: the very nice plug in by Gavin G]
(function($){
$.fn.focusTextToEnd = function(){
this.focus();
var $thisVal = this.val();
this.val('').val($thisVal);
return this;
}
}(jQuery));
$('#mytext').focusTextToEnd();
One can use these simple javascript within the input tag.
<input type="text" name="your_name" value="your_value"
onfocus="this.setSelectionRange(this.value.length, this.value.length);"
autofocus />
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Then you can just do:
input.putCursorAtEnd();