R.P.
R.P.

Reputation: 139

save ID on each item in loop so it can be used as a hyperlink, Jquery

I am generating items in list from the below code. In order for it to display correctly I need to create an html string. Each item in this list is supposed to become a hyperlink where you click on it and it reloads the page with new data, so I need to save the ID on each item in order to retrieve the correct data for that item What is the best way for me to do what I am trying to accomplish?

$(r.campuses).each(function(index, item) {
  if (item.campusID != 55) {
    var HTMLcontent = '<div class="ml-32 mt-16 mb"><a class="other-school"><label class="other-schools-list">' +
      item.campusName + '</label></a><br /></div>';
    $('.group').append(HTMLcontent);
  }
});

Upvotes: 0

Views: 166

Answers (1)

Benjie Wheeler
Benjie Wheeler

Reputation: 575

I'm not sure this is what you need but looks like you want to put the item.campusID in the href attribute of your a element.

UPDATE

Adding click listener to the code to handle user clicking on the link.

you can do it like this:

$(r.campuses).each(function(index, item) {
  if (item.campusID != 55) {
    var HTMLcontent = '<div class="ml-32 mt-16 mb"><a href="path/to/your/' + item.campusID + '" class="other-school"><label class="other-schools-list">' + item.campusName + '</label></a><br /></div>';
    $(HTMLcontent).on('click', function() {
      window.location.href = window.location.href + "?id=" + item.campusID;
    });
    $('.group').append(HTMLcontent);
  }
});

Just change path/to/your/ to your correct path.

Upvotes: 1

Related Questions