开发者

Focus input field with JQuery without selecting current value text

$("#开发者_运维百科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?


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.


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

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


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);


Have you tried this?

var txt = $("#myinputfield").val();
$("#myinputfield").focus();
$("#myinputfield").val( txt );


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();
    }
}


$(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.


This solution works very well for me:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜