Thursday, July 12, 2012

Jquery -> Dynamically add table rows/columns

/*
    Date:    12-july-12
    Code:    Jquery, Javascript
    Purpose: Add rows to a html table dynamically depending on the selection of checkboxes   
*/
 
function addSelectedItems(chkBox) {
 

    //the name of the checkbox is in the form of FilteredPeers[0].IsSelected where 0(zero) is the row index
    var rowindex = $(chkBox).attr('name').split("[")[1].split("]")[0];

   
//cell1 is the companyname which is also in the format FilteredPeers[0].CompanyName
    var field1 = document.getElementsByName('FilteredPeers[' + rowindex + '].CompanyName');

   
//Getting the value of the cell
    var companyname = $(field1).val();

   
/* Append columns to the table header row*/
    $('#tblSelected thead tr').append('<th>' + companyname + '</th>');

   
/* Append rows to a table */
    //        $('input[type="checkbox"]').each(function () {
    //            if ($(this).val() == 'true') {
    //                $('#tblFR').append('<tr id="1"><td colspan="2">Dyanmic row</td></tr>');
    //            } else {
    //                $('#tblFR tr').remove('<tr id="1">');
    //            }
    //        });

}