JQuery clone, replace number in id and name attributes

I understand that this question is similar to the one that was asked before, and maybe I do not receive it, because it is 9pm at night, but I would like to receive a small pointer on how to fix the problem. I know where I'm wrong. I just don't know how to fix it:

I am cloning a table row with 4 select blocks, and I want to clone identifiers and names, but increase id by one. This is what I have 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 takes the identifier and name of the first select and increments the id correctly, but applies it to all selections that are not what I want.

For clarity, the HTML string I am cloning is as follows:

 <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> 

Hopefully someone can point out where I'm going terribly wrong!

Thank you very much

+4
source share
2 answers

@Mark F, you gave me a hint in 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) ); }); ... }); 

It is amazing that good nights sleep and a push in the right direction can reach.

Thanks again.

+8
source

you select all select elements in addition to the line and change all names and identifiers.

 $("select", row).attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1) ); $("select", row).attr("id", $("select", row).attr("id").replace(/\d+/, rowCount1) ); 

It looks like you are trying to get each select in your cloned string, something like this.

 $(row).find("select").attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1) ); 
+1
source

Source: https://habr.com/ru/post/1484713/


All Articles