how to find a dynamic id in name attribute JQuery

Viewed 60

I have many inputs where to dynamically change the value of the name attribute, for example:

Select

<select class="form__input form__select select optional" id="js-customer-field" name="customer[customer_food_attributes][16321232322354][customer_id]"><option value="">Select</option>

...

<select class="form__input form__select select optional" id="js-customer-field" name="customer[customer_food_attributes][023912321331123][customer_id]"><option value="">Select</option>

I would like to take the value to apply to an event, but since the id's are random I don't know how to capture them

on this name attribute or any with random id:

"customer[customer_food_attributes][023912321331123][customer_id]"

$("customer[customer_food_attributes][023912321331123][customer_id]").on('change'), function(e, item) {...})

I would be very grateful if someone could help me build the attribute dynamically Thank you for your time in reading me.

2 Answers

It is not really clear to what you are trying to do. Could you maybe clarefy a little bit? Are you trying to change the name attribute of the select elements? Or do you want to bind an event to all select elements?

If the latter, I would do something like this (assuming you want to trigger the event on a value change):

$(".form__select").on("change", function(){
    // Get the name attribute
    let name = $(this).attr("name");
    // Do whatever you like, depending on the value of name
    // ...
};

You could just listen to change events from any select elements and check if the name matches the pattern.

This can be done with/without jQuery.

 // using jquery
$('select').on('change', function(e) {
    const regex = /customer\[customer_food_attributes\]\[(\d+)\]\[customer_id\]/;
    const match = e.target.name.match(regex);
    if(match){
        const id = match[1];
        // here is your id
        // do something with it
    }
});

// using vanilla js
document.addEventListener('change', function(e) {
    const regex = /customer\[customer_food_attributes\]\[(\d+)\]\[customer_id\]/;
    const match = e.target.name.match(regex);
    if(match){
        const id = match[1];
        // here is your id
        // do something with it
    }
});
Related