Search code examples
jqueryattr

Table Filter with Stackable.js - (How to copy <tr> data-attributes?)


I'm using stackable.js for a responsive table. This works great at generating a mobile friendly table (however) I'm also trying to incorporate a table filter that requires data attribute's to work. Unfortunately these data attributes do not copy over to the mobile version of the table so I need to figure out how to amend the script to include them.


I managed to work out something using jQuery .data() and a for loop.

var data = $(this).data(),
    tr_data = [];

for(key in data) {
    tr_data.push("data-"+key + "=" + data[key]);
}

This cycles through the <tr> to gather all attribute pairs and push them to an array. However, when adding the array to the markup the appended attributes are not correctly formatted.

They copy into the mobile table < tr > but the quotes are in the wrong place and the comma's need to be removed - (see below).

data-tags="Tag" 2,data-priority="Urgent,data-milestone=Milestone" 2,data-status="In" progress,data-assigneduser="Larry,data-taskId=1"

The attributes "should" match the desktop < tr > formatting - (see below).

data-task-id="1" data-assigned-user="Larry" data-status="In Progress" data-milestone="Milestone 2" data-priority="Urgent" data-tags="Tag 2"

CodePen here: https://codepen.io/jinch/pen/JjJbzww?editors=0010

Line #125 is where the array is created.

Line #135, #142, #145 ~ is where the "tr_data" variable array is added to the markup.

What am I doing wrong?


Solution

  • I managed to work out the formatting issue by adding quotes around the attribute value "'"+data[key]+"'". Also used join method '+tr_data.join(" ") +' to remove the commas.

    var data = $(this).data(),
        tr_data = [];
    
        for(key in data) {
          tr_data.push("data-"+key + "=" + "'"+data[key]+"'");
     }
    

    And this is one example how I added the array to the markup:

    bodyMarkup += '<tr class="' + tr_class +'" '+tr_data.join(" ") +'>';
    

    If in need of a table filter using stackable.js ~ here is a working CodePen: https://codepen.io/jinch/pen/JjJbzww?editors=0010