How to focus on a form input text field on page lo

2020-01-27 09:38发布

This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?

11条回答
Luminary・发光体
2楼-- · 2020-01-27 09:57

Sure:

<head>
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $("#myTextBox").focus();
        });
    </script>
</head>
<body>
    <input type="text" id="myTextBox">
</body>
查看更多
淡お忘
3楼-- · 2020-01-27 10:03

Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.

You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:

var anyFieldReceivedFocus = false;

function fieldReceivedFocus() {
    anyFieldReceivedFocus = true;
}

function focusFirstField() {
    if (!anyFieldReceivedFocus) {
        // Do jQuery focus stuff
    }
}


<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-27 10:04

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Hnady if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

查看更多
倾城 Initia
5楼-- · 2020-01-27 10:04

This is what I prefer to use:

<script type="text/javascript">
    $(document).ready(function () {
        $("#fieldID").focus(); 
    });
</script>
查看更多
啃猪蹄的小仙女
6楼-- · 2020-01-27 10:07

place after input

<script type="text/javascript">document.formname.inputname.focus();</script>
查看更多
Melony?
7楼-- · 2020-01-27 10:07

The Simple and easiest way to achieve this

$('#button').on('click', function () {
    $('.form-group input[type="text"]').attr('autofocus', 'true');
});
查看更多
登录 后发表回答