Search code examples
jqueryreplaceclone

Jquery clone, replace number in id and name attributes


I realise this question is similar to some that have been asked before and it's possible I'm not getting it because it's 9pm at night but I'd love to get a little pointer on how to fix the problem. I know where I'm going wrong I just don't know how to fix it:

I'm cloning a table row with 4 select boxes and I want to clone the id's and names but increment the id's by one. This is what i've got at the moment.

$(document).on("click", "#new_item", function() {
    var rowCount = $("#widget_location_options tbody>tr:last select").attr("id").match(/\d+/);
    var rowCount1 = rowCount*1 + 1;
    var row = $("#widget_location_options tbody>tr:last").clone(true);
    $("select option:selected", row).attr("selected", false);
    $("select", row).attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1) );
    $("select", row).attr("id", $("select", row).attr("id").replace(/\d+/, rowCount1) );
    row.insertAfter("#widget_location_options tbody>tr:last");
});

The problem is that it's taking the id & name of the first select and correctly incrementing the id but appying it to all selects which isn't what I want.

For clarity the HTML of the row I'm cloning looks like this:

<tr>
<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]">
<option value="value">label</option>
</select></td>

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]">
<option value="value">label</option>
</select></td>

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]">
<option value="value">label</option>
</select></td>

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]">
<option value="value">label</option>
</select></td></tr>

Hope someone can point out where I'm going horribly wrong!

Many thanks


Solution

  • @Mark F, you gave me a hint at the right direction - thanks. The actual solution looks like this:

    $(document).on("click", "#new_item", function() {
        ...
    
        $(row).find("select").each(function(){
            $(this).attr("name", $(this).attr("name").replace(/\d+/, rowCount1) );
        });
        $(row).find("select").each(function(){
            $(this).attr("id", $(this).attr("id").replace(/\d+/, rowCount1) );
        });
    
    
        ...
    });
    

    Amazing what a good nights sleep and a nudge in the right direction can achieve.

    Thanks again.