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条回答
一纸荒年 Trace。
2楼-- · 2020-01-27 10:11

You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.

<input type="text" name="some_field" autofocus>

Note this will not work on IE9 and lower.

查看更多
女痞
3楼-- · 2020-01-27 10:11

Why is everybody using jQuery for something simple as this.

<body OnLoad="document.myform.mytextfield.focus();">
查看更多
叛逆
4楼-- · 2020-01-27 10:13

Set focus on the first text field:

 $("input:text:visible:first").focus();

This also does the first text field, but you can change the [0] to another index:

$('input[@type="text"]')[0].focus(); 

Or, you can use the ID:

$("#someTextBox").focus();
查看更多
够拽才男人
5楼-- · 2020-01-27 10:16

HTML:

  <input id="search" size="10" />

jQuery:

$("#search").focus();
查看更多
欢心
6楼-- · 2020-01-27 10:16

The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:

$('#myTextBox:text:visible:first').focus();
查看更多
登录 后发表回答