How to select form input based on label inner HTML?

I have multiple forms that are dynamically created with different input names and id’s. The only thing unique they will have is the inner HTML of the label. Is it possible to select the input via the label inner HTML with jQuery? Here is an example of one of my patient date of birth blocks, there are many and all unique except for innerHTML.

<div class="iphorm-element-spacer iphorm-element-spacer-text iphorm_1_8-element-spacer">
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">events=Object { mouseover=[1], mouseout=[1]}handle=function()data=Object { InFieldLabels={...}}
    Patient DOB
    <span class="iphorm-required">*</span>
</label>
<div class="iphorm-input-wrap iphorm-input-wrap-text iphorm_1_8-input-wrap">
    <input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8" class="iphorm-element-text iphorm_1_8" type="text" value="" name="iphorm_1_8">events=Object { focus=[1], blur=[1], keydown=[1], more...}handle=function()
</div>
<div class="iphorm-errors-wrap iphorm-hidden"> </div>

Read More

This is in a WordPress Plugin and because we are building to allow employees to edit their sites (this is actually a WordPress Network), we do not want to alter the plugin if possible.
Note that the label “for” and the input “id” share the same dynamic key, so this might be a way to maybe get the id, but wanted to see if there is a shorter way of doing this.

Here I cleaned up what is likely not used…

<div>
<label for="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
    Patient DOB
    <span class="iphorm-required">*</span>
</label>
<div>
    <input id="iphorm_081a9e2e6b9c83d70496906bb4671904150cf4b43c0cb1_8">
</div>

Related posts

Leave a Reply

3 comments

  1. You can use the contains selector to select the Patient DOB labels, then find the related input.

    $('label:contains("Patient DOB")').parent('div').find('input');
    

    This assumes that the label and input are wrapped in the same div and may not work if more than one pair is in the same div. At least the first part will get you the labels that contain Patient DOB, then you can adjust the later parts to find the correct input element.

    For more help on jquery selectors, see the API.

    Here is a fiddle demonstrating this.

  2. var getForm = function(labelInnerHtml) {
        var $labels = jQuery('label');
        $labels.each(function() {
           if (jQuery(this).html() == labelInnerHtml) {
                var for_id = jQuery(this).attr('for');
                return jQuery('#'+for_id);
            }
        });
        return [];
    };​​