methuselah
methuselah

Reputation: 13206

Fire button click event when there are multiple classes on an element

How would I fire a button click event when a particular button is pressed (in this case the accept button).

I've tried the following but with little success:

Javascript

$('.notification-expand .Request .active-item > .accept-button').click(function () {
    alert("hello");
});

HTML

<div class="notification-expand Request active-item" style="display: block;">
    <div class="notification-body"></div>
    <br>
    <p>
        <button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
    </p>
    <div class="row">
        <div class="col-xs-6 expand-col">
            <button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
        </div>
        <div class="col-xs-6 expand-col">
            <button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
        </div>
    </div>
</div>

Fiddle here

Upvotes: 0

Views: 197

Answers (5)

Dayan
Dayan

Reputation: 8031

Just give the button an id and reference back to that.

HTML

<button id="btnSubmitData"> Ok Button </button>

JQuery Code

$('#btnSubmitData').click(function(){ ... });

You can also have multiple button Ids bind to the same event:

$('#btnAccept, #btnReject, #btnWarning').click(function () {
        alert("hello");
    });

Take a look at the updated Working Fiddle.

Upvotes: 1

alquist42
alquist42

Reputation: 739

try

$('.accept-button', $('.notification-expand.active-item')).click(function () {
    alert("hello");
});

or

$('.notification-expand.active-item')).find('.accept-button').click(function () {
    alert("hello");
});

Upvotes: 1

Mohamed Shaaban
Mohamed Shaaban

Reputation: 1169

You need to concatenate all classes without spaces to catch your target button

$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
    alert("hello");
});

See the updated snippet

Notice the syntax of ".className1.className2" instead of ".className1 .className2"

Upvotes: 2

You have error in your selector , it should look like this:

$('.notification-expand.Request.active-item .accept-button').click(function () {
    alert("hello");
});

Upvotes: 4

Giovanni Le Grand
Giovanni Le Grand

Reputation: 784

should be something like:

$('button.accept-button').click(function(){ ... });

there is really no need to go down the whole list if this is the whole code

----edit----

so when there are more items but only 1 active(i guess) then just target the active-item class:

$('div.active-item button.accept-button').click(function(){ ... });

Upvotes: 1

Related Questions