Guys i have post list where each post have own ID. I want with jquery to get that id from custom attribute. Problem is when i try to debug i get all time the some value.
This is html table that i list from database with PHP. Each post have specific ID.
Name | id
-------------------
Post 1 | 188
Post 2 | 189
Post 3 | 190
<i id="like" class="glyphicon glyphicon-heart" data-id="<?=$post->post_id;?>"></i> Like
So when i try to get value from data-id script all time return 188 number. When click on Post 1, post 2, post 3 all time value is 188!!! Whay ?
Here is JQuery:
isPostLiked: function() {
var isLiked = false;
var likeText = $("#like");
var itemId = likeText.attr("data-id");
// debug
Post.postLikeBtn.click(function() {
console.log(itemId);
});
//$.ajax({
// type: "post",
// url: baseurl + "/like/isLikedAjaxAction/"
//});
if (isLiked == true) {
likeText.css("color", "red");
}
},
It seems you are generating HTML in a loop. Remember Identifiers in HTML must be unique, you can use CSS class then Class Selector (“.class”) can be used. Modify you HTML as
<i class="like glyphicon glyphicon-heart" data-id="<?=$post->post_id;?>"></i> Like
Change click handlers and fetch ids using the current element context i.e. this
$('.like').click(function(){
var id= $(this).data('id');
});
Every element must have a unique id attribute. You cannot have more than one element with an id of "like." Try something like this instead:
<i class="like glyphicon glyphicon-heart" data-id="<?=$post->post_id;?>"></i> Like
Then define do this to set your callback:
$('.like').click(function() { /* your code here */ });