Search code examples
javascriptjqueryhtmlclone

Jquery iterate over function for each dynamically added select box


Having some issues with jquery and trying to figure out how to use the same function and iterate over select box's that are dynamically being added with jquery.clone().

here is a snippet of what is being cloned

<select name="expense_type" id="expense_type">
    <option value=""></option>
    <option value="daily_pay">Daily Pay</option>
    <option value="Lodge">Lodging</option>
    <option value="Meals">Meals</option>
    <option value="Mileage">Mileage</option>
    <option value="Telephone">Telephone</option>
    <option value="Expense">Expense</option>
    <option value="PaLandRecords">PA Land Records</option>
    <option value="Landex">Landex</option>
    <option value="Copies">Copies</option>
    <option value="Other">Other</option>
</select>

and here is my jquery code. Sorry I only post a snippet of my code the i variable is declared.

var i = 1;
$("#add").click(function () {
    $("#tr_clone").clone().find("input,select").each(function () {
        $(this).val('').attr("id", function (_, id) { return id + i });
    }).end().appendTo("table");
    i++;
});
$("#expense_type_" + i).change(function () {
    alert($(this).val());
});

So basically once a select box is cloned I'm trying to get jquery to automatically update it's self and create a change event so that regardless of the amount of select boxes on the form it will automatically alert the user of the new value after it has been changed any help would be great.


Solution

  • $("#add").click(function() {
        $("#tr_clone").clone().find("input,select").each(function() {
            $(this).val('').attr("id", function(_, id) {
                return id + i
            });
        }).end().appendTo("table");
    
        $("#expense_type_" + i).change(function() {
            alert($(this).val());
        });
    
        i++;
    });
    

    if you wann to use the same function for each select box you can do the following

    $('body').on('change', '.mySelector', function(){
        alert($(this).val());
    });