treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Trigger Click on Input when Label is Clicked

Last updated on:

Labels should have "for" attributes that match the ID of the input they are labeling. This means we can snag that attribute and use it in a selector to trigger a click on the input itself. Assuming of course you have some reason to watch for clicks on inputs.

var labelID;

$('label').click(function() {
       labelID = $(this).attr('for');
       $('#'+labelID).trigger('click');
});
View Comments

Comments

  1. TeMc
    Permalink to comment#

    Not sure if that’s what you mean, but Safari does this built-in.

  2. Bill Brown
    Permalink to comment#

    All browsers except IE will do this when you code it this way:


    <label><input id='my_input'/></label>

    IE requries this:

    <label for='my_input'><input id='my_input'/></label>

    • Sumedh

      Wonderful Man. Your comment is far better and helpful than this post..

  3. Yeah I really don’t see the point in this jQuery code. Using the “for” attribute of the LABEL tag, all browsers have this functionality already built-in. Kind of a useless post, really.

  4. Helpful for me especially with Gravity Forms (or anything that dynamically creates the form fields for you). One error though, $(‘#’+labelid).trigger(‘click’); should be $(‘#’+labelID).trigger(‘click’);

    Thanks

  5. Paula Lyon-Lee

    Brilliant piece of code just what I was looking for.

    This actually fixes the IE bug when you are using images within form labels.

    Normally what happens with a label is that when you click it the field it is for get focus, unfortunately IE for some reason or another seems to loose this functionality when you use images within form labels.

    Thanks
    Paula

Leave a Comment

Use markdown or basic HTML and be nice.