JQuery not working with same name of multiple elements

Tags: , , , ,



In Razor View of I have written the html code for table

<tbody>
                                @foreach (var item in Model.TodaysVM)
                                {
                                    <tr>
                                        <td>@item.OrderId</td>
                                        <td>@item.WorkOrderType</td>
                                        <td>@item.CustomerId</td>
                                        <td>@item.CustomerName</td>
                                        <td>@item.AppointmentDate</td>
                                        <td>
                                            <button class="btn btn-primary btn-sm" id="addCustomActivity" data-id=@item.OrderId>Add Custom Activity</button>
                                        </td>
                                    </tr>
                                }
                            </tbody>

Now Let’s say when click the button Add Custom Activity I need to alert the value of respective @item.orderID there might be a multiple row in the table and each row contains the button. My JQuery Code is :

 $("#addCustomActivity").click(function () {
                alert($(this).attr("data-id"));
            });

I works fine but the problem is the it only works for first row of the table. the button dosen’t works for second row. How I can fix this so that the button works for every row?

Answer

The problem is that ID must always be unique, If you have multiple elements with the same id it will always select the first element it finds with that id

Change class="btn btn-primary btn-sm" id="addCustomActivity" to class="btn btn-primary btn-sm addCustomActivity"

Then you can use:

$(".addCustomActivity").click(function () {
    alert($(this).attr("data-id"));
});

NOTE

Your title JQuery not working with same name of multiple elements would actually work, if you had name="addCustomActivity" and then your jQuery code would look like:

$("button[name=addCustomActivity]").click(function () {
    alert($(this).attr("data-id"));
});


Source: stackoverflow