w3resource

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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/jquery-exercises/jquery-events-exercise-18.php