JavaScript set focus to HTML form element

2019-01-02 20:19发布

I have a web form with a text box in it. How do I go about setting focus to the text box by default?

something like this:

<body onload='setFocusToTextBox()'>

so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.

<script>
function setFocusToTextBox(){
//What to do here
}
</script>

7条回答
几人难应
2楼-- · 2019-01-02 21:00

As mentioned earlier, document.forms works too.

function setFocusToTextBox( _element ) {
  document.forms[ 'myFormName' ].elements[ _element ].focus();
}

setFocusToTextBox( 0 );
// sets focus on first element of the form
查看更多
登录 后发表回答