Skip to content

JQuery not working with same name of multiple elements

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

                                @foreach (var item in Model.TodaysVM)
                                            <button class="btn btn-primary btn-sm" id="addCustomActivity" data-id=@item.OrderId>Add Custom Activity</button>

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 () {

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?



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 () {


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 () {