Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Table header is being deleted when deleting row from table

When I am deleting row from my table, also the table header is being deleted, how I can fix this?

$('#clubs tbody').on('click', '.deleteBtn', function() {
   $(this).closest('tr').remove();  
});

Button tag

<td>
  <button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" 
                     title=@DbResHtml.T("Delete", "Resources")></button>
</td>

My button have a class of .delete so when I click it, my row is deleted together with my table header.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My table have and id of clubs while table body have and id of clubsTBody.

Table

<div class="table-responsive">
  <table class="table table-striped my-4 " id="clubs">
    <thead>
      <tr>
        <th>@DbResHtml.T("#", "Resources")</th>
        <th>@DbResHtml.T("Клуб", "Resources")</th>
        <th>@DbResHtml.T("Лига", "Resources")</th>
        <th></th>
      </tr>
    </thead>
    <tbody id="clubsTBody">
@foreach (var club in Model.Player.PlayerClubs)
  {
      <tr>
        <td>@Html.DisplayFor(x => count)</td>
        <td>@Html.DisplayFor(x => club.Club.Name)</td>
        <td>@Html.DisplayFor(x => club.Club.League.LeagueType)</td>
        <td>
          <button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"
                             title=@DbResHtml.T("Delete", "Resources")></button>
        </td>
      </tr>
  count++;
  }
    </tbody>
  </table>
</div>

Also I am adding dynamically rows into my table.

$(document).ready(function() {
  $('#select2-3').change(function() {
    var cc  = $('#select2-3').val();
    var ids = [];
    for (let i = 0; i < cc.length;i++) {
      ids.push(cc[i]);
    }
    $.ajax({
      type    : "POST",
      url     : "@Url.Action("GetClubsById","Player")",
      data    : {"ids": ids},
      success : function(data) {
        console.log(data);
        $('#clubs tr').remove();
        var counter = 1;
        for (let i = 0; i < data.length; i++) {
          $("#clubsTBody").append("<tr><td>" + counter + "</td>"
            + "<td>" + data[i].name + "</td>"
            + "<td>" + data[i].league.leagueType + "</td>"
            + "<td>" + '<button  class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"  title=@DbResHtml.T("Delete", "Resources")></button>' + "</td>" 
            + "</tr >");
          counter++;
        }
      },
      error: function(req, status, error) {
          console.log(msg);
      }
    });
    
    $('.deleteBtn').on('click', function() {
      $(this).closest('tr').remove();

      var value = $(this).closest('tr').children('td:eq(1)').text();
      $(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
    });
  })
    
// /.../

})

The problem is here, when I am removing selected item from select list, without this code, everything is working perfectly but selected items doesn’t get deselected.

$(`#select2-3 option:selected:contains("${value}")`)
  .prop("selected", false)
  .parent()
  .trigger("change");

>Solution :

$(document).ready(function() {
        $('#select2-3').change(function() {
            var cc = $('#select2-3').val();
            var ids = [];
            for (let i = 0; i < cc.length;i++){
                ids.push(cc[i]);
            }

            $.ajax({
                type: "POST",
                url: "@Url.Action("GetClubsById","Player")",
                data: {"ids": ids},
                success: function(data) {
                    console.log(data);
                    $('#clubsTBody tr').remove();
                    var counter = 1;
                    for (let i = 0; i < data.length; i++) {
                    $("#clubsTBody").append("<tr><td>" + counter + "</td>"
                    + "<td>" + data[i].name + "</td>"
                    + "<td>" + data[i].league.leagueType + "</td>"
                    + "<td>" + '<button  class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"  title=@DbResHtml.T("Delete", "Resources")></button>' + "</td>" 
                    + "</tr >");
                        counter++;
                    }
                },
                error: function(req, status, error) {
                    console.log(msg);
                }
            });

          $('.deleteBtn').on('click', function() {
            $(this).closest('tr').remove();

            var value = $(this).closest('tr').children('td:eq(1)').text();
            $(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
        });
        });

You nee to write this: $(‘#clubsTBody tr’).remove(); instead of $(‘#clubs tr’).remove();
You are removing all the TR in Ajax Response instead of Only Body TRs

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading