Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting focus on input field on page load (so the user can start typing) in jQuery

I am trying to make it so that when the page loads, the user's mouse cursor is automatically in the input field, so he can start typing without having to move and click his mouse. However, it doesn't seem to work for me for some reason.

My HTML code:

<input type="text" placeholder="Search.." id="searchField">
  <button type="submit" id="searchButton">Submit</button>

My JS/jQuery code:

$(document).ready(function() {
     $("searchField").focus()             
})
like image 759
ondrejm Avatar asked Sep 14 '25 14:09

ondrejm


2 Answers

1.Need to add jQuery library

2.You forgot # in jQuery code.(As it need to be selector)

<input type="text" placeholder="Search.." id="searchField">
<button type="submit" id="searchButton">Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(document).ready(function() {
     $("#searchField").focus()             
});

working snippet:-

$(document).ready(function() {
 $("#searchField").focus()             
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" placeholder="Search.." id="searchField">
<button type="submit" id="searchButton">Submit</button>
like image 134
Anant Kumar Singh Avatar answered Sep 17 '25 06:09

Anant Kumar Singh


HTML already has that functionality, with the autofocus attribute. No need for JS.

Working snippet:

<input type="text" placeholder="Search.." id="searchField" autofocus>
<button type="submit" id="searchButton">Submit</button>
like image 35
blex Avatar answered Sep 17 '25 04:09

blex