Search code examples
jqueryarraysapicoursera-api

Dynamically assign unique id value to hyperlink onclick event


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");
        });

    }



}


  }); 
});

Solution

  • 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.