Reputation: 3050
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
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
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
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