ctrl
ctrl

Reputation: 25

jQuery .each only works for first item

I am trying to preload an html file whose contents will subsequently be used on several expandable buttons spread throughout a website.

The problem is that only the content of the first button of the page gets loaded this way, the rest of the buttons show nothing when expanded.

I do have noticed that there are other questions here on SO about similar issues, but none of the solutions I've come across seemed to work in this case. Therefore, any help will be greatly appreciated.

Relevant part of the script:

$(document).ready(function () {
     
    var thisLink = $("a.ajax-link");
    var targetUrl = thisLink.attr("data-href");
    var target = thisLink.data("ajaxtarget");
 
    $(target).each(function( index, btn ) {
        $(this).load(targetUrl, function () {
          console.log('Success');
        });
      });
    
});

If there is any other piece of information that could be of use to you, please let me know. Thank you very much for your time

Upvotes: 2

Views: 209

Answers (1)

Lapskaus
Lapskaus

Reputation: 1721

Assuming the selector a.ajax-link selects all your expandable links, then var thisLink = $("a.ajax-link"); holds an array of all your expandable link elements on your page. Therefore with var target = thisLink.data("ajaxtarget"); you only receive the data attribute of the first element in the array.

The solution is simple:

You need to run your foreach loop for every expandable link and get the corrosponding data from each of these links.

$(document).ready(function () {
   $.ajax({
     url: "http://example.com/path/to/html/file",
     dataType: "html",
     success: function(html) {
        $.each($("a.ajax-link"), function() {
          let targetUrl = $(this).data('href');
          let $target = $($(this).data('ajaxtarget'));
          $target.load(targetUrl, function() {
            console.log('success');
          });
        });
     }
    });
});

Upvotes: 2

Related Questions