Using closest to focus closest textbox

Jack Sniper picture Jack Sniper · Dec 27, 2013 · Viewed 9.4k times · Source

I'm trying to create the most efficient function for focusing a textbox upon clicking the label next to it. I have a working function, but its filled with a bunch of if statements. There are 16 textbox's in this form, so I don't want the function to have to go through 16 if statements every time a label is clicked. Here is my working code:

HTML

        <div>
          <div>
            <span class="form-label">Contact Name</span>
          </div>
          <div>
            <input type="text" name="name" id="signup_name">
          </div>
        </div>

        <div>
          <div>
            <span class="form-label">Email Address</span>
          </div>
          <div>
            <input type="email" name="email" id="signup_email">
          </div>
        </div>

jQuery

$('.signup_container .form-label').click(function() {
    labelName = $(this).html()
    if (labelName.indexOf("Contact Name") >= 0) {
        $('#signup_name').focus();
    }
    if (labelName.indexOf("Email Address") >= 0) {
        $('#signup_email').focus();
    }
});

Now I want to create something much smaller such as this:

jQuery:

$('.signup_container .form-label').click(function() {
    $(this).closest('input[type=text]').focus();
});

But I'm unable to get this function to perform properly. Is it possible to use closest and focus like this?

Answer

Igor Šarčević picture Igor Šarčević · Dec 27, 2013

The closest methods returns the closest parent of the element that matches the selector.

Here is the official documentation: http://api.jquery.com/closest/

A solution

Some other solution would be to use two times the parent selector and then the find one. Of course I assume that your html won't change.

$('.signup_container .form-label').click(function() {
    $(this).parent().parent().find('input[type=text]').focus();
});

A better solution

If you can it would be even nicer to do things like this.

<div class='inputGroup'>
 <div>
    <span class="form-label">Contact Name</span>
  </div>
  <div>
    <input type="text" name="name" id="signup_name">
  </div>
</div>

<div class='inputGroup'>
  <div>
    <span class="form-label">Email Address</span>
  </div>
  <div>
    <input type="email" name="email" id="signup_email">
  </div>
</div>

And then use the closest method to find the closest .inputGroup parent

$('.signup_container .form-label').click(function() {
    $(this).closest('.inputGroup').find('input[type=text]').focus();
});