HTML elements with the same ID

At the moment I'm working for a "like" system for news feed, there are multiple news feeds on 1 page which means there are multiple like buttons with the same ID. this is the jquery I use to like the posts:

$(document).ready(function(){
    $('#likebutton').click(function(){ 
        $.ajax({
            url : 'inc/ajax.php',
            type : 'POST',
            data : {
                action : 'like_post',
                poid : $('#likebutton').data('poid')
            },
            dataType : 'JSON',
            success : function(result) {
                if (result.xhr == 'success') {
                    $('#likebutton').attr('disabled','true');
                    $('#likes').html(parseInt($('#likes').html()) + 1);
                } else if (result.xhr == 'error'){
                    alert('An internal error occurred, try again later.')
                }
            }
        });
    });
    $('#unlikebutton').click(function(){
        $.ajax({
            url : 'inc/ajax.php',
            type : 'POST',
            data : {
                action : 'unlike_post',
                poid : $('#unlikebutton').data('poid')
            },
            dataType : 'JSON',
            success : function(result) {
                if (result.xhr == 'success') {
                    $('#unlikebutton').attr('disabled','true');
                    $('#likes').html(parseInt($('#likes').html()) - 1);
                } else if (result.xhr == 'error'){
                    alert('An internal error occured, try again later.')
                }
            }
        });
    });
});

Everything works fine until the point where it has to disable the like button and add 1 to the counter. What it does is disables all the like buttons on that page and I need to refresh the page to like another post. I know this is because there are more than 1 HTML elements that have the same ID but I can't give the unique ID's because the function that echoes the post and the javascript are on different pages and also if I would create unique ID's I'd have to repeat this function for every post on that page (10).

EDIT:

Relevant HTML

<div class='media-body'>
    <h4 class='media-heading'>post #1</h4>
    <p>post #1</p>
    <button data-poid="10" class="btn btn-link btn-xs likebutton" style="font-size: 14px;"><i class="fa fa-thumbs-up"></i>  <small>Like</small>
    </button>
    <h5 id='likes' style="display: inline;">0</h5>  <small>likes</small>
    <small style="cursor:pointer;" onClick="$('#comments10').toggle('slow');">Add Comment</small>
    <form action="" method="post" id="comments10" style="display:none;">
        <input type="hidden" name="id" value="10">
        <textarea style="width:100%;height:100px;" name="comment"></textarea>
        <br />
        <input type="submit" class="btn btn-primary" value="Add comment" />
    </form>
</div>

EDIT I was the biggest idiot editing the wrong page... i am so sorry for wasting everyone's time and @satapal's answer worked thank you very much!

Answers:

Answer

IDs must be unique in HTML. If you use that your HTML documents becomes invalid.

I would recommend you to use classes instead of duplicate ID.

You can select an element with a class using class selector

Description: Selects all elements with the given class.

Syntax

jQuery( ".class" )

Where

class: A class to search for. An element can have multiple classes; only one of them must match.

Modified Code to provide you an example how to use classes

$(document).ready(function () {
    $('.likebutton').click(function () {
        var self = this;
        $.ajax({
            url: 'inc/ajax.php',
            type: 'POST',
            data: {
                action: 'like_post',
                poid: $(self).data('poid')
            },
            dataType: 'JSON',
            success: function (result) {
                if(result.xhr == 'success') {
                    $(self).attr('disabled', 'true'); //Here I have used self
                    $('#likes').html(parseInt($('#likes').html()) + 1);
                } else if(result.xhr == 'error') {
                    alert('An internal error accoured, try again later.')
                }
            }
        });
    });
    $('.unlikebutton').click(function () {
        var self = this;
        $.ajax({
            url: 'inc/ajax.php',
            type: 'POST',
            data: {
                action: 'unlike_post',
                poid: $(self).data('poid')
            },
            dataType: 'JSON',
            success: function (result) {
                if(result.xhr == 'success') {
                    $(self).attr('disabled', 'true'); //Here I have used self
                    $('#likes').html(parseInt($('#likes').html()) - 1);
                } else if(result.xhr == 'error') {
                    alert('An internal error accoured, try again later.')
                }
            }
        });
    });
});

EDIT:

As per updated HTML, You should use

var likes = $(self).parent().find('.likes');
likes.html(parseInt(likes.html()) - 1); 

instead of

$('#likes').html(parseInt($('#likes').html()) - 1); //Use +1 for like and -1 for unlike
Answer

You could check for the .likes in the scope of a parent:

$(document).ready(function(){
    $('.likebutton').click(function(){
        var self = this;
        $.ajax({
            url : 'inc/ajax.php',
            type : 'POST',
            data : {
                action : 'like_post',
                poid : $(self).data('poid')
            },
            dataType : 'JSON',
            success : function(result) {
                if (result.xhr == 'success') {
                    $(self).attr('disabled','true');
                    $($(self).parent()).find('.likes').html(parseInt($($(self).parent()).find('.likes').html()) + 1);
                } else if (result.xhr == 'error'){
                    alert('An internal error occurred, try again later.')
                }
            }
        });
    });
    $('.unlikebutton').click(function(){
        var self = this;
        $.ajax({
            url : 'inc/ajax.php',
            type : 'POST',
            data : {
                action : 'unlike_post',
                poid : $(self).data('poid')
            },
            dataType : 'JSON',
            success : function(result) {
                if (result.xhr == 'success') {
                    $(self).attr('disabled','true');
                    $($(self).parent()).find('.likes').html(parseInt($($(self).parent()).find('.likes').html()) - 1);
                } else if (result.xhr == 'error'){
                    alert('An internal error occured, try again later.')
                }
            }
        });
    });
});

Make sure that the class likes, unlikebutton and likebutton are added. And, make sure you add a parent. Live Demo.

HTML Changes

<div class='media-body'>
    <h4 class='media-heading'>post #1</h4>
    <p>post #1</p>
    <button data-poid="10" class="btn btn-link btn-xs likebutton" style="font-size: 14px;"><i class="fa fa-thumbs-up"></i>  <small>Like</small>
    </button>
    <h5 class='likes' style="display: inline;">0</h5>  <small>likes</small>
    <small style="cursor:pointer;" onClick="$('#comments10').toggle('slow');">Add Comment</small>
    <form action="" method="post" id="comments10" style="display:none;">
        <input type="hidden" name="id" value="10">
        <textarea style="width:100%;height:100px;" name="comment"></textarea>
        <br />
        <input type="submit" class="btn btn-primary" value="Add comment" />
    </form>
</div>
Answer

You shouldn't use the same ID more than once on the same page. That's why it's called ID. :) You should use classes instead, and then in your jQuery, use the this keyword to access the properties of the clicked element. Example:

$('.likebutton').click(function(){ 
    $.ajax({
        url : 'inc/ajax.php',
        type : 'POST',
        data : {
            action : 'like_post',
            poid : $(this).data('poid')
        },
        dataType : 'JSON',
        success : function(result) {
            if (result.xhr == 'success') {
                $(this).attr('disabled','true');
                $('#likes').html(parseInt($('#likes').html()) + 1);
            } else if (result.xhr == 'error'){
                alert('An internal error accoured, try again later.')
        } }
    });
});
Answer

It looks to me like you are using almost exactly the same code there. Make it more reusable doing something like

var createLikeHandler = function (action, buttonSelector, counterSelector) {
    return function () {
        $.ajax({
            url : 'inc/ajax.php',
            type : 'POST',
            data : {
                action : action + '_post',
                poid : $(buttonSelector).data('poid')
            },
            dataType : 'JSON',
            success : function(result) {
                if (result.xhr == 'success') {
                    $(buttonSelector).attr('disabled','true');
                    var increment = action === 'like' ? 1 : -1
                    $(counterSelector).html(parseInt($(counterSelector).html()) + increment);
                } else if (result.xhr == 'error'){
                    alert('An internal error accoured, try again later.')
            }
        }

    }
};

Then you can use class selectors as previously recommended and automate the creation, for example doing

var likeUI = [{
    like: '.like1',
    unlike: '.unlike1',
    counter: '.counter1'
},
{
    like: '.like2',
    unlike: '.unlike2',
    counter: '.counter2'
}];

likeUI.forEach(function (likeElement) {
    $(likeElement.like).click(createLikeHandler('like', likeElement.like, likeElement.counter));
    $(likeElement.unlike).click(createLikeHandler('unlike', likeElement.unlike, likeElement.counter));
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.