jQuery: Set the focus to the first input box

jQuery Events : Exercise-18 with Solution

Set the focus to the first input box.

Sample Data :

<p>First Name: <input type="text" id='field1'></p>
<p>Last Name: <input type="password" id='field2'></p>


HTML Code :

<!DOCTYPE html>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>Set the focus to the first input box</title>
<p>User ID <input type="text" id='field1'></p>
<p>Password <input type="password" id='field2' > </p>

JavaScript Code:

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

Live Demo:

See the Pen jquery-events-exercise-18 by w3resource (@w3resource) on CodePen.

Contribute your code and comments through Disqus.

Previous: Attach a function to the focus event. The focus event occurs (display a message regarding the text field) when the <input> field gets focus.
Next: Set background color of an element when the element (or any elements inside it) gets focus or loses focus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.