dimanche 23 octobre 2016

Showing checked checkbox rows first in the table

I have written a code which is populating a html table using ajax call using the following code -

$.ajax({
            type: "POST",
            url: "my_url",
            data: JSON.stringify(result),
            async: true,
            dataType: "json",
            contentType: "application/json; charset= Shift-JIS",
            success: function (response) {
            glResp = response;
            populateTable(glResp);                        
              },
           error: function (error) {
            console.log(error);
            //alert("Error!!");
              }
         });

The data is being correctly shown on the table with a checkbox in front of each row. Now I want to show the rows which have checked checkboxes in the table first and rest of the rows after that. I have written the following code but it doesn`t seem to work. Anyone can help?

function populateTable(finalObject) {
    var obj = finalObject;

    var headers1=['Name','City','Job','Salary'];
    var table = $("<table id='my-table' />");
    var columns = headers1;             
    columns.unshift('');
    var columnCount = columns.length;
    var row = $(table[0].insertRow(-1));

    for (var i = 0; i < columnCount; i++) {
    if (i == 0) {
            var headerCell = $("<th><input type='button' id='sort'></th>");
            row.append(headerCell);
        }

        else {

            var headerCell = $("<th/>");
            headerCell.html([columns[i]]);
            row.append(headerCell);
        }
    }

    $.each(obj, function (i, obj) {
         $row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.City + '</td><td>' + obj.Job + '</td><td>' + obj.Salary + '</td></tr>';
      table.append(row);
    });


    var dvTable = $("#dvCSV");
    dvTable.html("");
    dvTable.append(table);


}

$(function () {

    $('#sort').on('click', function () {
        var newTable = $('<table class="table"></table>');
        $('.my-table').find('tr').each(function ($index, $value) {
            if ($(this).find('input[type=checkbox]').is(':checked')) {
                newTable.prepend($(this));
            } else {
                newTable.append($(this));
            }
        });
        $('.table').replaceWith(newTable);
    });

}); 




Aucun commentaire:

Enregistrer un commentaire