How to focus on a form input text field on page load using jQuery?

前端 未结 11 1185
天命终不由人
天命终不由人 2020-11-28 18:56

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

11条回答
  •  一整个雨季
    2020-11-28 19:10

    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 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
        }
    }
    
    
    
    
    

提交回复
热议问题