Targeting Dynamic Element IDs with jQuery

When elements are added dynamically through a scripting language (usually by a database pull) they can have sequential identifiers in one or more of their attributes. For this example, a series of checkboxes that, when checked, will populate an input box by matching up the numeric portion of the id attribute.

To make the matching easier to set up and understand, setting the id’s should be consistent. In this example the id’s will have a pattern of prefix_00. The elements to be matched will have the same pattern.

<p>
    <input type="checkbox" id="checkbox_01" name="checkbox" value="red was checked" />red<br />
    <input type="checkbox" id="checkbox_02" name="checkbox_02" value="green was checked" />green<br />
    <input type="checkbox" id="checkbox_03" name="checkbox_03" value="blue was checked" />blue
</p>

<table>
    <tr>
        <td>color 01<input type="text" id="color_01" name="color_01" /></td>
    </tr>
    <tr>
        <td>color 02<input type="text" id="color_02" name="color_02" /></td>
    </tr>
    <tr>
        <td>color 03<input type="text" id="color_03" name="color_03" /></td>
    </tr>
</table>

The jquery/javacript will strip off the prefix of an element’s id to grab the numeric value. It will then concatenate the numeric value onto the prefix of the matching element.

The function to grab the number:

function getNum(element, attrPrefix) {
    //set prefix, get number
    var prefix = attrPrefix;
    var num = element.attr("id").substring((prefix.length));
    return num;
}

A checkbox change function calls the getNum function and concatenates the id for the matching element. Then it sets the value of the matched element.

$(":checkbox").change(function() {
    var num = getNum($(this), "checkbox_");
    if ($(this).is(":checked")) {
        $("#color_" + num).val($(this).val());
    } else {
        $("#color_" + num).val("");
    }
});

Fiddle Demo:

Posted in jquery. Tags: , . Permalink. Both comments and trackbacks are closed.

One Comment

  1. January 22, 2012 at 4:05 pm | Permalink

    Thanks! Helps me so much! :)