...">

Cloning table rows and changing newline identifiers in jQuery

I have a table containing the following information:

<table id="Requirements"> <tr> <td> <select id="Id.0" name="Id.0" onChange="changeTextBox();">... </td> <td> <select id="Comparator.0" name="Comparator.0" onChange="changeTextBox();">... </td> <td> <input type="text" id="Integer.0" name="Integer.0"/>... </td> <td> <select id="Value.0" name="Value.0">... </td> </tr> </table> 

and add button.

 <input type="button" id="addButton" value="Add" onClick="appendRow();"/> 

I need the appendRow() function to not only clone the previous line, but change its identifier and name to Id.1, Id.2, Comparator.1, Comparator.2, etc. Since some of the dropdown menus have so many meanings, it is not possible to create one giant append statement to recreate each line. How can I change the attributes of a clone when I create it? Thanks!

Edit: identifiers should be in the format .0, .1. This form submits a URL that reads them as such

Edit 2: Code

 function appendRow() { $("QualificationRequirements").append($("QualificationRequirements tr:last").clone()); } 

Do not try to change identifiers, just a simple clone function that I cannot get to work.

+4
source share
1 answer

You can try this ( DEMO )

HTML:

 <table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data"> <tr> <td>SelectOne</td> <td>Select two</td> <!-- More Headers --> </tr> <tr> <td> <select id="Id.0" name="Id.0">...</select> </td> <!-- More tds --> <td><input type="button" class="addButton" value="Add" /></td> </tr> </table> 

JS:

 $(function(){ $("#table-data").on('click', 'input.addButton', function() { var $tr = $(this).closest('tr'); var allTrs = $tr.closest('table').find('tr'); var lastTr = allTrs[allTrs.length-1]; var $clone = $(lastTr).clone(); $clone.find('td').each(function(){ var el = $(this).find(':first-child'); var id = el.attr('id') || null; if(id) { var i = id.substr(id.length-1); var prefix = id.substr(0, (id.length-1)); el.attr('id', prefix+(+i+1)); el.attr('name', prefix+(+i+1)); } }); $clone.find('input:text').val(''); $tr.closest('table').append($clone); }); $("#table-data").on('change', 'select', function(){ var val = $(this).val(); $(this).closest('tr').find('input:text').val(val); }); }); 
+8
source

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


All Articles