jQuery

jQuery Focus Textbox When Div is clicked

Have you ever wanted to focus textbox when div is clicked but always wondered how to do it? In this article, I am going to share with you a very easy way to automatically set focus to an input textbox when a Div is clicked,  using jQuery.  The actual code is just 1 line, so it’s super easy to follow along. Read on to find out more.

Examples on using jQuery to Focus Textbox when Div is clicked

Let’s assume that we have a div with ID “#my_div” and an input box with ID “name”. Here is how you can focus the “name” input box when the div “my_div” is clicked:

Full Source code:

<html>
<head>
<title>Focus textbox when div is clicked with jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
#my_div {
border: 1px solid #F00;
}
</style>
</head>

<body>

<div id="my_div">This is my div. Click on me to focus the "name" input box</div>
<br>
<br>

<form name="form1" method="post" action="">
<label for="Name">Name</label>
<input type="text" name="name" id="name">
</form>

<script type="text/javascript">

$('#my_div').click(function() {

$('#name').focus();

});

</script>
</body>
</html>

You can simply rename the input box and/or the div ID to whatever you like and then update the jQuery code as well. If you would rather use the class of an element to set focus on the input box, you can do it like so:

$('.my_div_class').click(function() {

$('#name').focus();

});

The above code assumes that you have a class “my_div_class” applied to your Div.

Simple, isn’t it?

Do you know of any other ways to use jQuery to set focus on textbox when div is clicked? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*