13

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 from key board or any other device is caught by this element. I have tried the following code with no effect:

<body>
    <input type="text" id="exp" maxlength="16"></input>
    <input type="text" id="exp2" maxlength="16"></input>
    <script>
        $("#exp").hide();
        $("#exp").focus();
        $("#exp2").keypress(function(){
            alert($("#exp").val());
        });
    </script>
</body>

make any suggestions. jquery solution will be preferred.

slash197
  • 9,028
  • 6
  • 41
  • 70
jack sparrow
  • 173
  • 1
  • 1
  • 9

3 Answers3

15

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>
Nathan Wall
  • 6,426
  • 2
  • 22
  • 23
  • by doing this the #exp will never be able to come back to it's previous place –  Jun 25 '12 at 06:56
  • Usually you don't want a hidden text box which is being used to capture keys to come back into view. But you can bring it back to its previous place: `$('#exp').css('position', 'static');` – Nathan Wall Jun 25 '12 at 06:57
  • That meets my requirements...although it was not what I was looking for...it sems a bit of the box solution....:)...thanks anyways... – jack sparrow Jun 26 '12 at 03:42
  • 3
    ;-) Believe it or not, this is a pretty standard solution. Cheers! – Nathan Wall Jun 26 '12 at 10:02
  • true story!! :P (you may also try to z-index it down, but it may give problems with some mobile browsers..) – Anze Jan 23 '14 at 03:51
1
visibility:hidden; 
position: absolute;

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

mhenry1384
  • 7,538
  • 5
  • 55
  • 74
0

This is possible via async/await where the code to select the input only runs after the code to display the input returns its fulfilled promise.

let selectInput = async () => {
    await setInputDisplayBlock();
    document
        .getElementById("input")
        .focus();
};
selectInput();
Chris
  • 500
  • 6
  • 25