w3resource
jquery exercises

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 :

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

Solution:

HTML Code :

<!DOCTYPE html>
<html>
<head>
<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>
</head>
<body>
<p>User ID <input type="text" id='field1'></p>
<p>Password <input type="password" id='field2' > </p>
</body>
</html>

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 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?



New Content: Composer: Dependency manager for PHP, R Programming