RWS
RWS

Reputation: 560

Watch for multiple clicks on any buttons with Jquery

I have several buttons on page:

<button id="button-event-status-4" data-closed="0" data-id="4" class="btn-danger">closed</button>
<button id="button-event-status-10" data-closed="1" data-id="10" class="btn-success">OPEN</button>

I need to pick a click at any of them (can be more than one at any moment.

$(document).ready(function() {
    $("[id^='button-event-status-']").click(function() {
      alert ('it works');
    });
});

The code above not working. What am I missing here?

Upvotes: 0

Views: 121

Answers (1)

SRK
SRK

Reputation: 3496

You can simply give a same class to all button and bind click event to the class.

$(document).ready(function() {
    $(".sameclass").click(function() {
      alert ('it works');
    });
});


<button id="button-event-status-4" data-closed="0" data-id="4" class="btn-danger sameclass">closed</button>
<button id="button-event-status-10" data-closed="1" data-id="10" class="btn-success sameclass">OPEN</button>

Update

Since the buttons are added dynamically you need to bind click event on each button. Use this code to get it work.

 $(document).ready(function() {
        $(document).on("click",".sameclass",function() {
          alert ('it works');
        });
    });

Upvotes: 1

Related Questions