John
John

Reputation: 3050

Many buttons, jquery

jQuery:

$("#direction").click(function() {
    var direction = $(this).text();
    alert(direction);
}

HTML

<button id="direction">South</button>
<button id="direction">North</button>

Only the first button alerts the text. I don't understand why. How can I fix this?

Upvotes: 0

Views: 77

Answers (3)

james_bond
james_bond

Reputation: 6906

You can't have two elements with the same id, use classes if you want to reference multiple elements at once, something like:

<button class="direction">South</button>
<button class="direction">North</button>

And then in your script:

 $(".direction").click(function() {
    var direction = $(this).text();
    alert(direction);
});

Upvotes: 1

Ryan
Ryan

Reputation: 1797

You can't have two elements with the same id, what you could do is give them the same class and then add the event handler on that.

Example:

<button class="directionBtn">South</button>
<button class="directionBtn">North</button>

$(".directionBtn").click(function() {
                var direction = $(this).text();
                alert(direction);
});

Upvotes: 7

David Thomas
David Thomas

Reputation: 253436

It's invalid to have multiple elements with the same id (an id must be unique within the document); as jQuery presumably implements document.getElementById() internally, this will only ever (correctly) return the first element it encounters with that id.

In your case you should use a class of direction, and select based upon that:

$('.direction').click(
    function(){/*...*/});

Upvotes: 2

Related Questions