trying to set focus on a hidden text box

前端 未结 2 1296
感情败类
感情败类 2021-02-04 09:38

I am trying to set focus on a hidden text box. I want that when the body or div containing the text box loads the focus should be on the particular text box so that any input fr

相关标签:
2条回答
  • 2021-02-04 10:14

    You can't set focus to a text box that is hidden through the hide method. Instead, you need to move it off screen.

    <body>
    <!-- it's better to close inputs this way for the sake of older browsers -->
    <input type="text" id="exp" maxlength="16" />
    <input type="text" id="exp2" maxlength="16" />
    <script>
    // Move the text box off screen
    $("#exp").css({
        position: 'absolute',
        top: '-100px'
    });
    $("#exp").focus();
    $("#exp2").keypress(function(){
    alert($("#exp").val());
    });
    </script>
    </body>
    
    0 讨论(0)
  • 2021-02-04 10:18
    visibility:hidden; 
    position: absolute;
    

    Works in Chrome 53, and seems cleaner than trying to shift the element offscreen as in Nathan Wall's answer.

    0 讨论(0)
提交回复
热议问题