Bokchee 88 Bokchee 88 - 2 months ago 11
JSON Question

How to an id data from external json file and show id number in url , when item is clicked with jQuery

I am trying to figure it out how to get id, from json file when an item is clicked.
What i have so far, this is just a basic json, to return name and picture from a movie.
$( document ).ready( function () {

$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '#jsonLoad' ).append( "<a href='' id='itemsHolder'>" +
"<div class='titleHolder'>" +
"<h2 >" + data[i].name +"</h2>"+
"</div>"+
"<div class='posterHolder'>"+ data[i].posterPath +"</div>" +
"</a>")

}
} )

} );


This is my json file from my folder.

[{
"id":1,
"name": "Godzilla",
"year": 1998,
"releaseDate": "20 May 1988",
"runtime": "2h 19mm",
"director": "Roland Emmerich",
"screenplay": "Dean Devlin and Roland Emmerich",

"imdb": 5.3,

"boxOffice": "$130,000,000 ",
"openingWeekend": "$55,726,951",
"posterPath": " <img src='imgsMovie/Godzilla1998/GodzillaPoster.jpg'/>"
}]

Answer

First of all, your are duplicating the DOM ID in below line -

$( '#jsonLoad' ).append( "<a href='' id='itemsHolder'>" +

This you can fix with something like -

$( '#jsonLoad' ).append( "<a href='' id='itemsHolder'" + data[i].name + ">" +

This way each DOM element will have unique ID on the page. Now you need to bind the click event to dynamically created "" tag, so your script will be like this -

$.getJSON( "js/appjson.json", function ( data ) {
    for ( var i = 0; i < data.length; i++ ) {
        $( '#jsonLoad' ).append( "<a href='' class='className' id='itemsHolder'" + data[i].id + " data-id='" + data[i].id + "'>" +
        "<div class='titleHolder'>" +
        "<h2 >" + data[i].name +"</h2>"+
        "</div>"+
        "<div class='posterHolder'>"+ data[i].posterPath +"</div>" +
        "</a>")

     }
  });

  $(document).on("click", "a.className", function(){
      //This will show element ID
      alert($(this).attr('id'));

      //This will show the ID you received from your JSON
      alert($(this).data('id'));
  });

In above script I have used custom data attribute to store ID received from your JSON, also to create the unique element ID, I have concatinated the ID received from JSON with "itemsHolder" string.

Hope this will solve your issue.

Comments