Reputation: 2055
I have mulitple elements
<a href='#' id='Favorites[]' name='Favorites1'>1</a>
<a href='#' id='Favorites[]' name='Favorites2'>2</a>
<a href='#' id='Favorites[]' name='Favorites..'>..</a>
<a href='#' id='Favorites[]' name='Favorites1000'>1000</a>
I trying to get name of clicked element
$("#Favorites").on('click', function() {
alert(this.name);
});
But it works only for first element, others elements not react on click event
How to fix that?
Upvotes: 0
Views: 43
Reputation: 115212
id
should be unique, so you need to use class
instead, otherwise it will only select the first dom element with the id
$(".Favorites").on('click', function() {
alert(this.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href='#' class='Favorites' name='Favorites1'>1</a>
<a href='#' class='Favorites' name='Favorites2'>2</a>
<a href='#' class='Favorites' name='Favorites..'>3</a>
<a href='#' class='Favorites' name='Favorites1000'>4</a>
Upvotes: 3
Reputation: 109
I think the issue is that the jquery selector #Favourites is only intended to find a single 'id' with that value so the others are ignored.
You could consider converting the 'Favourites' to being a class like:
<a href='#' class='Favorites' name='Favorites1'>1</a>
<a href='#' class='Favorites' name='Favorites2'>2</a>
<a href='#' class='Favorites' name='Favorites..'>..</a>
<a href='#' class='Favorites' name='Favorites1000'>1000</a>
then use
$('.Favorites').on('click', function() {
alert(this.name);
});
I'm pretty sure you should only have one 'id' attribute per dom with a specific value typically. http://www.w3schools.com/tags/att_global_id.asp w3schools id attribute documentation
Upvotes: 1