javascript - Text box -> start typing right away instead of clicking the box - Stack Overflow

I have a search bar, and when I open the search bar I want to start typing right away and do not want t

I have a search bar, and when I open the search bar I want to start typing right away and do not want to click on the text box for that to happen.

I tried to use myTextBoxId.click() ( because when you click it, you can start typing ) but it didn't work.

I have a search bar, and when I open the search bar I want to start typing right away and do not want to click on the text box for that to happen.

I tried to use myTextBoxId.click() ( because when you click it, you can start typing ) but it didn't work.

Share Improve this question edited Oct 10, 2016 at 17:50 Vaibhav Mule 5,1464 gold badges37 silver badges52 bronze badges asked Oct 10, 2016 at 16:59 Hen EliezerHen Eliezer 213 bronze badges 1
  • 1 Use myTextBoxId.focus() instead. – Mohammad Commented Oct 10, 2016 at 17:01
Add a ment  | 

6 Answers 6

Reset to default 3

You have to

document.getElementById(" <put your Id here> ").focus();

to set focus on the given element.

You can set the focus once you load the page, or trigger the focus on keydown (this way even if you set the focus out of the input - when you start typing the focus will get there again).

$(function() {
  $('#searchbox').focus();

  $(document).on('keydown', function() {
    $('#searchbox').focus();
  });
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchbox" />

since you've got 17 of the same answer, how about a new one!

HTML5 has an autofocus attribute that does this. no JS required.

<input type='text' autofocus>

See here.

Use .focus() instead of .click()

var myTextBoxId = document.getElementById("myTextBoxId")
myTextBoxId.focus();
<input id="myTextBoxId" />

If <input id="myTextBoxId" />, you can use following scripts

Jquery:

$(function() {
 $("#myTextBoxId").focus();
});

Javascript:

window.onload = function() {
 document.getElementById("myTextBoxId").focus();
};

or

<body onLoad="document.getElementById('myTextBoxId').focus();">

You can use myTextBox.focus() to achieve this. Note that you can call focus() after myTextBox variable is set to point to your actual text box. See: HTMLElement focus

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744203475a4562993.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信