Skip to content Skip to sidebar Skip to footer

How To Match Id In Javascript For Dynamically Added Field On Html?

In our rails app, dynamic fields can be added to the form. Here is a html source code for the dynamically added field order_order_items_attributes_1413563163040_unit_price:

Solution 1:

You have to first decide what algorithm you're using for matching the id values. Based on your comments (it is not specified precistly in your question), it appears you want to find all ids that start with "order_order_items_attributes_" and end with "_unit_price" and have a sequence of digits between them.

You can do that like this by find all the ids that start with the thing you want and then filtering them to things that only match all three criteria:

// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_pricevar orderItemRegex = /^order_supplier_id_\d+_unit_price$/;
$("[id^='order_supplier_id_']").filter(function(index) {
    return orderItemRegex.test(this.id);
}).change(function() {
    // this will be only the ids that match
});

This uses jQuery to make a list of all objects that have an id that starts with "order_supplier_id_". It then filters through that list eliminating any objects who don't match the full regex /^order_supplier_id_\d+_unit_price$/ that defines your pattern and then hooks up the .change() event handler to only the objects that pass the regex test.

Solution 2:

Use the for attribute of your <label>:

var selector = $('.decimal.required.control-label').eq(0).attr('for'),
    element = $('#'+selector);

console.log(element);
// [<input id="order_order_items_attributes_1413563163040_unit_price" ... >]

Solution 3:

You can use an attribute selector to match an id that "contains" the specified value, using [attr*=value]. Like:

$("[id*='order_supplier_id']").change(function() {

});

MDN's docs on attribute selectors specifies the kinds of selectors you can use to match the attribute, among them:

[attr*=value] Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

Solution 4:

You could maintain an array of element IDs that gets updated each time the form element is added. Then call your change method on the elements in your array. But that isn't necessary if the change event callback is identical for all the new elements. Just call it on the class.

Post a Comment for "How To Match Id In Javascript For Dynamically Added Field On Html?"