SC.Cee SC.Cee - 1 year ago 96
Javascript Question

Asp.net core delete button not working properly

I have a view like this:

<div class="GridContainer">
<div>
<div class="row gridHeader">
<div class="small-9 columns">Member Name</div>
<div class="small-2 columns">Date Registered</div>
</div>
@foreach (var member in Model.Members)
{
<div class="row">
<div class="small-9 columns">@member.MemberName</a></div>
<div class="small-2 columns">@member.DateRegistered</div>
<input type="hidden" asp-for="@member.Id" />
<a id="btnMemberDelete" href="#">Delete</a>
</div>
}
</div>




my javascript:

<script type="text/javascript">
$(document).ready(function () {
$('#btnMemberDelete').click(function () {
var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
var url = '@Url.Action("DeleteMembers", "Member")' + "?id=" + id;
openMemberDialog(url);
});
});
</script>


The delete button only works for the very first row at the moment. If say I have 4 rows the other 3's delete button won't even register. It won't even open the dialog box. Is there something I'm missing here as the code seems to be correct to me.

Thanks!

Answer Source

Fiddle here

As answerd above you need to have a uniqe ID or use a class. in my solution above I use a class like so:

  $(document).ready(function () {
        $('.btnMemberDelete').click(function (e) {
        e.preventDefault();
            var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();

           console.log(id)
        });
    });

Also correct your html:

@foreach (var member in Model.Members)
{
    <div class="row">
        <div class="small-9 columns">@member.MemberName</a></div> // remove the '</a>' here
        <div class="small-2 columns">@member.DateRegistered</div>
        <input type="hidden" asp-for="@member.Id" />
        <a class="btnMemberDelete" href="#">Delete</a>
    </div>
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download