javascriptjquerydatatables

how can i send the checked row to the first at datatables


This code actually works adding row, however when i checked the primary contact it didnt send to the first row instead it send to the last, kindly help me to fix this.

  //add row in contact
  $(document).ready(function () {
      var table = $('#lv_Lead_Contact_Information-datatable').DataTable({
          dom: "t"
      });

      //ensure the primary contract is only one
      $(document).on('change', '.primary-contact-checkbox', function () {
          if (this.checked) {
              // Uncheck all other checkboxes
              $('.primary-contact-checkbox').not(this).prop('checked', false);

              // Get the row of the checked checkbox
              var row = $(this).closest('tr');

              // Move the row to the top of the table
              row.fadeOut(function () {
                  table.row(row).remove().draw(false);
                  table.row.add(row[0]).draw(false);
                  row.fadeIn();
              });
          }
      });

      $(document).on('click', '#btnAddContact', function () {
          table.row.add([
              '<input type="checkbox" class="form-check-input primary-contact-checkbox" style="vertical-align: middle; margin-left: 21px;">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="text" class="form-control form-control-borderless">',
              '<input type="checkbox" class="" style="vertical-align: middle; margin-left: 19px;">',
              '<input type="text" class="form-control form-control-borderless">'
          ]).draw();
      });
  });

Solution

  • I think what you are looking for is when you select a primary contact row, that row should automatically move to the first row of the table.

    $(document).ready(function() {
    $('#lv_Lead_Contact_Information-datatable').on('click', '.primary-contact-checkbox', function() {
        var $row = $(this).closest('tr'); // Get the row containing the clicked checkbox
        var $tbody = $row.closest('tbody'); // Get the table body
    
        // Remove the row from its current position and insert it at the top
        $row.remove().prependTo($tbody);
    });
    

    });