Litash
Litash

Reputation: 182

Dynamically add rows into a table using data from another table-jQuery

I have two table on my page like the picture shown here.enter image description here

What I want to do is:

  1. select rows in the Source Table
  2. read the data in ID field, Name field from the Source Table, and also the value of radio button.
  3. Form these data as rows of Target Table and append these rows into Target Table.

Now Im using two arrays to store the ID and Name that read from Source Table, but im a bit confused about how to form a row for the Target Table.

$('#btnLinkCase').click(function (event) {
var caseID = $('#caseID').text();
var linkedIDArr = []; //array list for selected id
var linkedNameArr = []; //array list for selected name
$('#linkCaseTable tbody tr td:nth-child(2)').each(function (index, el) { //store each paire of <tr> into array
    linkedIDArr.push(el);
});
$('#linkCaseTable tbody tr td:last-child').each(function (index, el) { //store each paire of <tr> into array
    linkedNameArr.push(el);
});
$.each(linkedCaseIDArr, function (index, val) {
    //whats next?
});
});

Please see all source code here

Any ideas of doing this? Thanks in advance

Edit: If multiple rows are selected they will use the same value from the radio button. eg: two rows are selected and "Type 1" is checked. In target table, their relationship all are "Type 1". I hope I have explained myself..

Upvotes: 1

Views: 2410

Answers (1)

codingrose
codingrose

Reputation: 15699

Try:

$('button').click(function (event) {
    $("#sourceTable tr:gt(0)").each(function(){
        var th = $(this);
        console.log("dfg")
        if($(th).find("input[name='link-cbx']").is(":checked")){ //assuming ids are unique remove condition if you do notwant so
            var id = $(th).find("td:eq(1)").text();
            var name = $(th).find("td:eq(7)").text();
            var type = "Type "+$("input[name='linkType']:checked").val();
            if($("#targetTable:contains('"+id+"')").length < 1){            
                $("#targetTable").append("<tr><td>"+id+"</td><td>"+name+"</td><td>"+type+"</td></tr>");
            }
        }
    });
});

Updated fiddle here.

Upvotes: 2

Related Questions