34

I have a series of input elements each with a few <div> tags separate.
I like to have if where I can click on any of the <div> and it will focus on an input.
Is this possible and if so can anyone give ideas on script?

1
  • 2
    It is possible but have you considered using labels? I think you shouldn't rely on JavaScript for simple stuff like this when there are dedicated HTML tags for that purpose.
    – apnerve
    Apr 15, 2012 at 16:53

6 Answers 6

47

I don't see a reason why you need JS to do this when such feature is already provided in HTML.

<label for="YOURID">The clickable region<label>
<input id="YOURID" type="text" />
2
  • 1
    This is exactly what I was looking for! Thanks Dec 3, 2018 at 20:42
  • 2
    This saved me 8 years later!
    – Iltharion
    Oct 20, 2020 at 9:07
27

Try this with jquery:

$('#yourdiv').click(function() {
     $('#yourfield').focus();
});
0
16

Try this :

<input id="myInput" />
<div onclick="document.getElementById('myInput').focus(); return false;"></div>
1
  • 1
    the div in this example is not click-able as it has no dimension.
    – apnerve
    Apr 15, 2012 at 16:55
5
$('div').click(function() {
    $(this).find('input[type="text"]').focus();
});​

LIVE DEMO

2
  • 1
    Like this one over the other solutions as this is more generic and uses unobtrusive JS.
    – apnerve
    Apr 15, 2012 at 17:03
  • Thanks for the warm feedback! I liked it too as I wrote it... :) LOL
    – gdoron
    Apr 15, 2012 at 17:05
2
  1. using javascript (call .focus() on the input element)
  2. using wrapped around your div (makes only sense if the div is the label)
1
  1. USING HTML ("for") :

    HTML provides this functionality. Using "for" "id" you can easily achieve it.

 <label for="idname">Click Here to Reach Input<label>
 <input id="idname" type="text">
  1. USING jQuery ("focus")

$(".classname").click(function(){

$("input").focus(); })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.