Reputation: 11861
I have these 3 divs:
<div id="home_type">2 Storey</div>
<div id="home_type">Bungalow/ Bungalow Loft</div>
<div id="home_type">Townhome</div>
and I have this onclick event:
$('#home_type').click(function(){
alert('hi');
});
but it only works for the first item, here is my jfiddle (which also doesn't work, throwing the error Uncaught ReferenceError: $ is not defined
)
http://jsfiddle.net/o1arL1q7/1/
When I click on an item on my site, I get no errors and I only get the alert for the first item. How can I fix this?
Upvotes: 1
Views: 627
Reputation: 4233
This is because the id attribute must be unique. Try this (replacing id for a class):
HTML
<div class="home_type">2 Storey</div>
<div class="home_type">Bungalow/ Bungalow Loft</div>
<div class="home_type">Townhome</div>
JS
$('.home_type').click(function(){
alert('hi');
});
*The error thrown by jsFidle is because is missing a jQuery reference. You can include it in the Framework & Extensions menu.
Upvotes: 7
Reputation: 5250
You cannot have multiple elements in the DOM with the same ID. You would need to make those classes or change their ID's
HTML
<div class="home_type">2 Storey</div>
<div class="home_type">Bungalow/ Bungalow Loft</div>
<div class="home_type">Townhome</div>
JS
$('.home_type').click(function(){
alert('hi');
});
http://jsfiddle.net/o1arL1q7/4/
Upvotes: 1
Reputation: 60413
ID
's must be unique. The problem is you are trying to use the same ID multiple times so only the first found will work. Use a class instead.
<div class="home_type">2 Storey</div>
<div class="home_type">Bungalow/ Bungalow Loft</div>
<div class="home_type">Townhome</div>
And the JS:
$('.home_type').click(function(){
alert($(this).text());
});
Upvotes: 3