ondrejm
ondrejm

Reputation: 164

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

Upvotes: 4

Views: 1248

Answers (2)

blex
blex

Reputation: 25634

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>

Upvotes: 2

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

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>

Upvotes: 2

Related Questions