简体   繁体   中英

How to get more data from json array when a value in option tag is selected jquery

I'm trying to display more info of the museum when a museum name is clicked fro the option dropdown box. I am getting my data from a json array. I was able to populate the option box with the name of the museum but could not display more details. Could anyone please help me with this. I'm using jquery for this code.

function getMuseums() {

    var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo()\" />");
    var info = $("<span>Select Museum: </span>")

    $.get("museums.php",function(data,status) {
        var response = '';
        var json = $.parseJSON(data);
        museums = json.museums;
        $.each(museums, function (index, item) {

            $('<option />').attr({"value" : index}).text(item.museum_name).appendTo(museumSelect);

            /*response += "<option value='"+index+"'>" + item.museum_name + "</option>";
            $("#museumlist").html(response);*/

        });

        $('#content').empty().append(info, museumSelect);
        $("<div id=\"museumDetails\" />").appendTo("#MuseumDiv");

        getMuseumInfo()

    });
}

function getMuseumInfo() {
    var museum_id = $("#museumlist").val();
    selectedMuseumid = museum_id;
    $("#MuseumDiv").empty().append("<div id=\"museumDetails\"/>");

    var url = "museums.php?museum_id=" +escape(museum_id);

    $.get(url,function(data,status) {
        var json = $.parseJSON(data);
        museums = json.museums;

        var museum_name = museums.museum_name;
        var museum_description = museums.museum_description;

        var museumInfo = "<h3>" + museum_name + "</h3><p>" + museum_description + "</p>";

        $("#museumDetails").empty().append(museumInfo);

    });
}

You can pass option value to your function as a parameter getMuseumInfo(this.value) :

  var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo(this.value)\" />");

And than you can use iterate through museums and check if index is the same as option value, and then print only properties for that item.

$.each(museums, function(index, item) {    
    if (index == id) {
      var museumInfo = "<h3>" + item.museum_name + "</h3><p>" + item.museum_description + "</p>";    
      $("#MuseumDiv").empty().append(museumInfo);
    }
});

But better check working code (also turn on console in app): codePen

NOTE: I make example of request to create JSON data. I make get request to url: https://api.myjson.com/bins/58j10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM