Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to set focus on a hidden text box

Tags:

jquery

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.

like image 688
jack sparrow Avatar asked Jun 25 '12 06:06

jack sparrow


1 Answers

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>
like image 195
Nathan Wall Avatar answered Oct 30 '22 15:10

Nathan Wall