Mahydul Islam Shajal
Mahydul Islam Shajal

Reputation: 232

How to Iterate a list of list data to fill html table in JQuery

I have a table like this

<table>
        <tr>
            <td class="text-center">
                <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>
               </td>
               <td class="text-center">
                <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>
               </td>
               <td class="text-center">
                <input type="button" value="Details" style="color: Red;" id="btnDetails" class="clsbtnDet"/>
              </td>
        </tr>
     </table>

What I want is to iterate a list and fill those fields and there is a secondary list of each row (Contains Employee Details) inside the main one and that secondary list data need to fill a modal which initiate by clicking the "Details "button.

Any help will be much appreciated.

Upvotes: 2

Views: 928

Answers (1)

You can use .each() loop function which allows you to loop item(row) one by one at a time. It will passes the index (an integer) and the actual element that you can use like the following.

function primaryTable(list){

    $.each(list, function (i, mainList){
      <tr>
           <td class="text-center">
           <input class="form-control clsEmployeeId" id="txtEmployeeId" type="text" id="employeeId"  value="' + mainList.EmployeeId + '"/>
           </td> 
           <td class="text-center">
           <input class="form-control clsEmployeeName" id="txtEmployeeName" type="text" id="employeeName"  value="' + mainList.EmployeeName + '"/>
           </td>
           <td class="text-center">
           <input type="button" value="Detail" style="color: Red;" id="btnDetails" class="clsbtnDet" data-detail="'+ JSON.stringify(mainList.DetailList) + '"/>
           </td>
      </tr>
     });
}

At the Button field you can pass a list through the data-* attribute which is used to store custom data.

After storing your secondary list details data, you could get that list in the button click event by the following code..

var detail_data = $(this).attr('data-detail')); 

var json_detail=new Array(); 

json_detail = json_detail = JSON.parse(detail_data);   // Parse list data as JSON

Then pass this "json_detail" list to a your modal function and use .each() loop onece again to fill up your modal.

Upvotes: 1

Related Questions