I have 2 identical tables on a single form in a process. I need to copy the data from table 1 to table 2. How would I go about doing that with JavaScript? There are drop-downs, number fields, and checkboxes in each table.
Question
Question
How to Copy Values in Table 1 to Table 2 in Same Form?
asked on October 5, 2016
•
Show version history
2
0
Answer
SELECTED ANSWER
replied on October 5, 2016
You definitely can do this with Javascript. It can be a little complicated to do this in a completely general way without some assumptions. I will assume the following: 1) Your tables have the same column headers (need some feature to identify which values from the source match which values in the destination) 2) You have CSS classes on your tables (SourceTable and DestTable for my code below).
Other than that, this should be pretty generic. I had mine trigger when a button was pressed on the form (hence the button event handler wrapping the whole thing).
$(document).ready(function(){ $('#CopyTable').click(function(){ //Make the tables the same size var sLen = $('.SourceTable tbody tr').length; var dLen = $('.DestTable tbody tr').length; if (sLen > dLen){ for(var j=0; j< sLen-dLen; j++){ $('.DestTable .cf-table-add-row').click(); } } else if (dLen > sLen){ for(var j=0; j< dLen-sLen; j++){ $('.DestTable tbody tr:last-child .cf-table-delete').click(); } } //Copy the data $('.SourceTable tbody tr').each(function(){ var i = $(this).index(); $(this).find('td').each(function(){ var title = $(this).attr('data-title'); //Check if this is a Radio button or Checkbox item, handle it accordingly if ($(this).find('span.choice').length >0){ $(this).find('span.choice').each(function(){ var eIndex = $(this).index(); $('.DestTable tbody tr:nth-child('+(i+1).toString()+') td[data-title="'+title+'"] div span:nth-child('+(eIndex+1).toString()+') input').prop('checked',$(this).find('input').is(':checked')); }); } else { //Otherwise, just copy the one input/select element $('.DestTable tbody tr:nth-child('+(i+1).toString()+') td[data-title="'+title+'"] [id^="Field"]').val($(this).find('[id^="Field"]').val()); } }); }); }); });
4
0
Replies
You are not allowed to reply in this post.
You are not allowed to follow up in this post.