简体   繁体   English

使用JQuery聚焦输入字段而不选择当前值文本

[英]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? 如何在不选择文本的情况下聚焦字段?

我已经搜索了一下,有点发现你应该重点将你的值重新设置到所需的字段。

这样的事情如何在聚焦后将输入字段的值设置为自身?

$("#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. 如果在Firefox中,光标出现在输入的开头,并且您希望它在最后,则需要稍作修改。 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/ 演示: http//jsfiddle.net/X7Y8S/

i took the code & demo from ahren's answer in other topic, i think it's helpful. 我从其他主题的ahren的答案中获取了代码和演示,我认为这很有帮助。

This solution works very well for me: 这个解决方案对我很有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM