29
$("#myinputfield").focus();

Doing that on an input field with it's value already set causes the current value to be selected. How can I focus the field without selecting the text?

Alastair Stuart
  • 4,165
  • 3
  • 36
  • 33
  • Why would you want to do this? If you tab to a field it is also selected. This is standard user behavior. Where do you expect the caret to be? (Start of the text? End of the text?) – Phrogz Apr 11 '12 at 17:46
  • @Phrogz it could behave the same way textareas do now (contents are not selected when tabbing into one). It's not the same across browsers but as long as it's consistent.. – MSpreij Apr 07 '17 at 12:33

7 Answers7

27

I've searched around a bit and kinda found out that you should re-set your value into the desired field after it is focussed on.

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
26

How about something like this where you set the value of the input field to itself after focusing it?

$("#myinputfield").focus().val($("#myinputfield").val());
bensie
  • 5,373
  • 1
  • 31
  • 34
7

Other answers suggest setting the value of the input field to itself after focusing it. If in Firefox, the cursor appears at the start of the input and you want it at the end, then a slight modification is required. You will have to set the value as empty first and then set it to the previous value.

var value = $("#myinputfield").val();
$("#myinputfield").focus().val('').val(value);
Manish Singh
  • 5,848
  • 4
  • 43
  • 31
3

Have you tried this?

var txt = $("#myinputfield").val();
$("#myinputfield").focus();
$("#myinputfield").val( txt );
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0
function focusField(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();
    }
}
John Smith
  • 55
  • 1
  • 10
0
$(document).ready(function() {
    var $field = $("#formloginusername"),
        oldVal = $field.val();
    $field.focus().val('').val(oldVal);
});

DEMO: http://jsfiddle.net/X7Y8S/

i took the code & demo from ahren's answer in other topic, i think it's helpful.

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
0

This solution works very well for me:

$("#myinputfield").focus(function (event) {
  var value = $("#myinputfield").val();
  setTimeout(function() {
    $("#myinputfield").val(value);
  },10);
});