Search code examples
javascriptjqueryarraysarrayobject

How to get selected checkbox table row with each td data attributes to array objects?


Here is my Html code block I loaded table data from rest api and i want to get array object from each row td data attributes selected using the checkbox

<tr>
  <th scope='row' class='product-item-check'><input class='product-item-checkbox' type='checkbox' name='select-product' value='"+obj.pk_productId+"'></th>
  <td data-th_name='"+th_cell+"' data-td_name='"+td_cell+"' >" + td_cell + "</td>
</tr>

My Sample Code

$(document).on('click','.product-item-checkbox',function(){
        var thName;
        var tdName;
        var td;
        var checkedValue =  $('.product-item-checkbox:checked').closest('tr').find('td').map(function(i, v){
            thName = $(this).data('th_name');
            tdName = $(this).data('td_name');
            td = {
                "thead":thName,
                "tdata":tdName
            }
            return td;
        }).get();
        console.log(checkedValue);
});

Current OutPut ![Text](https://stackoverflow.com/image.jpg)
Expected Output

[
  {
    "pk_productId": 1940690,
    "productCode": "abcmkk",
    "productDescription": "Sample Description",
    "callout": 12qwww,
    "product_type": "woven",
    "product_image": null,
    "status": 1234,
  },
  {
    "pk_productId": 1940690,
    "productCode": "abcmkk",
    "productDescription": "Sample Description",
    "callout": 12qwww,
    "product_type": "woven",
    "product_image": null,
    "status": 1234,
  }
]

Solution

  • If I am understanding this correctly, you are wanting to get the selected row(s) in JSON format?

    While it is not an 'apples to apples' demonstration (as far as the data being used), the idea/logic remains the same...something like this should do the trick:

    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    td,
    th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }
    
    tr:nth-child(even) {
      background-color: #dddddd;
    }
    <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>
    <table id="my-table"></table>
    <h1 id="selected-items-title"></h1>
    <pre id="selected-items"></pre>
    <script>
        /**
         * GLOBAL DATA
         */
        let GLOBALS = {
            apiData: [ // PRETEND YOU ARE GETTING THIS DATA FROM A REST API
                { company: "Alfreds Futterkiste", name: "Maria Anders", country: "Germany" }, 
                { company: "Centro comercial Moctezuma", name: "Francisco Chang", country: "Mexico" }, 
                { company: "Ernst Handel", name: "Roland Mendel", country: "Austria" }
            ],
            tableData: "<tr><th></th><th>Company</th><th>Name</th><th>Country</th></tr>",
        }
    
        /**
         * DOCUMENT READY
         */
        $(document).ready(function () {
            // Add our API data to our table on load
            GLOBALS.apiData.forEach(item => {
                GLOBALS.tableData += `
                <tr>
                    <td><input class='product-item-checkbox' type='checkbox' name='select-product'/></td>
                    <td data-th_name="company" data-td_name="${item.company}">${item.company}</td>
                    <td data-th_name="name" data-td_name="${item.name}">${item.name}</td>
                    <td data-th_name="country" data-td_name="${item.country}">${item.country}</td>
                </tr>`;
            });
            $("#my-table").html(GLOBALS.tableData);
        });
    
        /**
         * EVENT .product-item-checkbox CLICK
         */
        $(document).on('click', '.product-item-checkbox', function () {
            // Finds all checked checkboxes and adds contents to array
            let selectedData = [];
            $('.product-item-checkbox:checkbox:checked').each((index, checkbox) => {
                let thName, tdName;
                let td = {};    
                $(checkbox).closest('tr').find('td').each(function (i, v) {
                    thName = $(this).data('th_name');
                    tdName = $(this).data('td_name');
                    if (thName !== undefined) {
                        td[thName] = tdName;
                    }                
                }).get();
                if (td) selectedData[selectedData.length] = td
            });
            
            if (selectedData.length > 0) {
                $("#selected-items-title").html("Selected Items:");
                $("#selected-items").show();
                $("#selected-items").html(JSON.stringify(selectedData, null, 2));
                console.log(selectedData);
            } else {
                $("#selected-items-title").html(""); 
                $("#selected-items").hide();
            }                 
        });
    </script>