Kamil Czaja Kamil Czaja - 2 months ago 6
jQuery Question

Why it's work only for first button?

I showing a list of items like this:

enter image description here

Why my code work only for first button? When I'm click to other one nothing happens.

$(document).ready(function() {
$("#js-toggle-attendance").click(function (e) {
var button = $(e.target);
$.post("/api/attendances", { gigId: button.attr("data-gig-id") }).done(function() {
button.removeClass("btn-default").addClass("btn-info").text("Ide");
}).fail(function() {
alert("Coś poszło nie tak :(");
});
});
});

Answer

I think you have used same id in that button.... so can you change it to class?

ID Selector rule in jQuery

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

Check on DOC

PATCH in jQuery ID Selector

Using attribute selector you can select multiple element and bind event on all element. here I have passed attribute selector using [] not #id. This is only patch for select maultiple element of same id not follow this at all

 $("[id='js-toggle-attendance']").click(function (e) {
        var button = $(this);
        $.post("/api/attendances", { gigId: button.attr("data-gig-id") }).done(function() {
            button.removeClass("btn-default").addClass("btn-info").text("Ide");
        }).fail(function() {
            alert("Coś poszło nie tak :(");
        });
    });