0

I have a jQuery script where somebody can click a button to add this item to their favorites. Now, the problem is I want to add this button several times on the page - the exact same button with the same code. When I click one of the buttons, the first one gets updated but the others don't. Is there any way to update ALL the matching IDs? In other words, run this action for all matching cases on the page, except for the first one?

The code is like this:

$(document).on('click','#add-to-list',function (e) {
               e.preventDefault();
               var id = $(this).data("id");
               $.ajax({
                 url: "http://xxx.xxx.xxx.xxx/add_to_list?id=" + id,
                 type: "GET",
                 dataType: 'json',
                 success: function(json) {
                     if(json.valid == 1) {

                         $("#list-button").hide();
                         $("#list-response").html('Added to Favorites');
                         $("#list-response").show();

                     }
                 },
                 timeout: 10000
               });
             });

And then on the page obviously I have multiple instances of

<div id="list-button">
 (button here)
</div>
<div id="list-response">
 (initially hidden)
</div>

2 Answers2

1

in jquery id will work only on single button and class will work on every button so for this action you have to use class instead of id please follow this link --

What's the difference between class and id in jQuery?

Community
  • 1
  • 1
Sorav Garg
  • 1,116
  • 1
  • 9
  • 26
0

ID of an element must be unique, the ID selector will fetch only the first element with the given ID.

In your case you can use classes instead of ID like then use traversal methods to target the proper element to show/hide

$(document).on('click', '.add-to-list', function (e) {
    e.preventDefault();
    var $this = $(this);
    var id = $this.data("id");
    $.ajax({
        url: "http://xxx.xxx.xxx.xxx/add_to_list?id=" + id,
        type: "GET",
        dataType: 'json',
        success: function (json) {
            if (json.valid == 1) {
                $this.closest('.list-button').hide().next().html('Added to Favorites').show();
            }
        },
        timeout: 10000
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="list-button">(button here)</div>
<div class="list-response">(initially hidden)</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531