Search code examples
jqueryjsonbackground-image

how to get json data based on html values using jquery?


I am a beginner in jquery, but I want to finish my project.

I need your help guys, I want if I make html

<li value="bca"></li>
<li value="bni"></li>
<li value="bri"></li>
<li value="mandiri"></li>
etc....

jquery gets json data based on the html value. then after getting it, I want to add the style background-image attribute based on that li value, the result will be like this

<li style="background-image:url("images/bca.png");" value="bni"></li>

this is the json file

[
   {
     "id": "bca",
     "image": "https://lh3.googleusercontent.com/-DzsioYaEw00/XJx4ldwgXbI/AAAAAAAAFOA/6xR4vKNHJnYPzyAmN_sike27rzTozXW8QCLcBGAs/h110/bca.png"
   },
   {
     "id": "bni",
     "image": "https://lh3.googleusercontent.com/-Km8RS__aFmY/XJx4lSZom7I/AAAAAAAAFOE/D6BYDFfRpUQdKILGREKGtKN8lLsjMijzACLcBGAs/h107/bni.png"
   },
   {
     "id": "bri",
     "image": "https://lh3.googleusercontent.com/-_si-RcoPgn8/XJx4laAI9DI/AAAAAAAAFN8/H6p0uAGp5LsjeETFJCO0wrX0IVRUMRsOQCLcBGAs/h71/bri.png"
   },
   {
     "id": "mandiri",
     "image": "https://lh3.googleusercontent.com/-7wME_gGOqlE/XJx4nKuMKoI/AAAAAAAAFOQ/e_g1zof81zA4RtoLvhXId-u5bbwynm2fgCLcBGAs/h105/mandiri.png"
   }
]

this my jquery

$(document).ready(function() {
  $.getJSON('https://vhlan.com', function(data) {
    $.each(data, function(key, icon) { // "icon" to get data from json file example icon.image
    // I don't know this part
      });
    });
  });

Solution

  • You can try this :

    $(document).ready(function() {
      $.getJSON('https://api.myjson.com/bins/yrgg4', function(data) {
        $.each(data, function(key, icon) { 
                $("li[value='" + icon.id + "']").css("background", "url(" + icon.image + ") no-repeat");
          });
        });
      });
    

    More : visit this