Reputation: 5105
I have the following code in my MVC 5 Razor View
@foreach (var colleague in Model.ColleagueList) {
<tr>
<td>
<button class="btn btn-danger btn-xs" id="btnDelete" data-id="@colleague.AssessorID">
Delete
</button>
</td>
</tr>
}
I then have this JQuery code
$(document).ready(function () {
$('#btnDelete').click(function() {
alert("Delete Button Clicked");
});
});
The for loop in the Razor View spits out several rows, however, when the user clicks on the Delete button, the alert only pops up for the first row, but not any of the other rows.
Can anyone see why this is happening?
Thanks.
Upvotes: 0
Views: 1057
Reputation: 11731
try below code :-
$('.btn.btn-danger').click(function() {
alert("Delete Button Clicked");
});
You have used id but it should be unique but you are using foreach it means duplication of the ids so try using class selecter as above.
Demo :-
Upvotes: 1
Reputation: 6398
Bcoz of foreach
all element will have same id so use class instead
@foreach (var colleague in Model.ColleagueList) {
<tr>
<td>
<button class="btnDelete btn btn-danger btn-xs" data-id="@colleague.AssessorID">
Delete
</button>
</td>
</tr>
}
$('.btn.btn-danger').click(function() {
alert("Delete Button Clicked");
});
Upvotes: 1
Reputation: 82241
You should use class selector instead of id selector. id selector selects first element in matched selector. also ids should be unique:
$('.btn.btn-danger').click(function() {
alert("Delete Button Clicked");
});
Upvotes: 3