Deleting row in table using Jquery in mvc project

I am generating the following html

code

<table>
        @for (int i = 0; i < Model.listUsers.Count; i++)
        {
            <tr>

                <td> @Html.DisplayFor(m => m.listUsers[i].Name)</td>
                <td>   @Html.DisplayFor(m => m.listUsers[i].Phone) </td>
                <td>
                    <button type="button" id="delete" data-id="@Model.listUsers[i].ID">Delete</button>
                </td>
            </tr>
        }
</table>

      

I want to delete a line,

<script>
    $(document).ready(function () {
        $("#delete").on("click", function () {
            var tr = $(this).closest('tr');
                tr.remove();
            });
    });

</script>

      

Doing this removes the line, but it only works the first time, i.e. just one time.

How can I delete any line?

+3


source to share


4 answers


IDs in HTML must be unique , use class instead, you can use Class Selector (".class") .

Selects all elements with the given class.

Html



<button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>

      

Script

$(document).ready(function () {
    $(".delete").on("click", function () {
        var tr = $(this).closest('tr');
        tr.remove();
    });
}); 

      

+3


source


You are generating duplicate attributes id

for your button which is invalid html and the script will only be called once because you are removing the button. Instead, remove id

and use the class name instead

<button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>

      



and change your script to

$(".delete").on("click", function () {
  var tr = $(this).closest('tr');
  tr.remove();
});

      

+3


source


You create a button with the same id

several times, which is not allowed html

, and every time you apply a selector to it, it selects the first element it finds in the DOM with the strikeout ID . Make it id

unique by adding a model id and add an attribute to the button class

:

<button type="button" class="delete" id="delete_@(Model.listUsers[i].ID)" data-id="@Model.listUsers[i].ID">Delete</button>

      

Now apply the click event for the class:

$(".delete").on("click", function () {
    var tr = $(this).closest('tr');
    tr.remove();
});

      

+3


source


replace this id with class because id is duplicate

<script type="text/javascript">
 $(document).ready(function(){
  $(".delete").on("click", function () {
            var tr = $(this).closest('tr');
                tr.remove();
            });
 });


</script>

<tr>

<td> @Html.DisplayFor(m => m.listUsers[i].Name)</td>
<td>   @Html.DisplayFor(m => m.listUsers[i].Phone) </td>
<td>
    <button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>
</td>

      

+1


source







All Articles