0

I am trying to iterate through a JSON response object to create a list of Category Items. I am trying to assign the unique Category ID value to each hyperlink so that when a user clicks on the hyperlink they will go to a page 2 and the page will then filter based on the selected Category Id. I am stuck on a logic error in my FOR LOOP where all of the Category Ids are being assigned to the one hyperlink. Also, is there a better way to pass data between HTML pages?

FIDDLE

$(document).ready(function() {


  $.ajax({
url: "https://api.coursera.org/api/catalog.v1/categories",
type: 'GET',
dataType: "json",
success: function(data) {
    //alert(data.elements.length);


        for(var i = 0; i < data.elements.length; i++)
    {                       
        $("#courseLink").append("<a href='page2.html?CatId="+data.elements[i].id+"'>"+data.elements[i].name+"</a><br/>"); 
         $("#courseLink").click(function() {
            $("#test").append("work");
        });

    }



}


  }); 
});
Josh J
  • 6,813
  • 3
  • 25
  • 47
  • Your fiddle is showing multiple hyperlinks created, each with a different CatID.. Seems to be working as expected yes? – StaticVoid Jun 15 '15 at 17:26
  • You're right. Is adding a Catid parameter to the url the best way to pass the catid value to the next page? – BlackBerry Special Jun 15 '15 at 17:35
  • Yes, this is generally accepted. Some would use a server-side Session variable, but for most implementations this is not needed as it simply wastes resources. – StaticVoid Jun 15 '15 at 17:37
  • Why not build the other menu server side? You can cache results for faster output and not use up client side resources on generating links on each load. – MiltoxBeyond Jun 15 '15 at 17:47

1 Answers1

0

There are several problems here.

Problem 1:

You were trying to append links inside #courseLink, which is also a link (<a> tag).

Problem 2:

$("#courseLink").click(function() {
  $("#test").append("work");
});

The click event binding was happening at each iteration, which means that the word "work" will be appended as many times as there are iterations in you form. Also, the event should be bound to a class selector instead of id (.courseLink instead of #courseLink) since ids should be unique.

I modified your fiddle in order to append the word "work" only once for each click.

lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48