Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

jquery - Populating drop down with json object

I have managed to populate my drop down menu with a json object, which worked fine. Currently I am trying to display an image which is in a hidden div based on an option selected from the drop down. As the drop down is populated by the json object how would I retrieve the image data.

Html

<form>
    <fieldset id="autoHeight">
        <legend>pod</legend>
        <h2>Cars</h2>
        <select name="drop_down" id="dropDownCars">
            <option value="None" selected="Selected">Select type</option>
        </select>
    </fieldset>
</form>
<div id="showBmw" class="hidden">
    <a href="http://cdn.iphoneincanada.ca/wp-content/uploads/2012/08/white-bmw.jpg"></a>
</div>

JSON File

{
    Cars: [{
        "CarType": "BMW",
        "carID": "bmw123"
    }, {
        "CarType": "mercedes",
        "carID": "merc123"
    }, {
        "CarType": "volvo",
        "carID": "vol123r"
    }, {
        "CarType": "ford",
        "carID": "ford123"
    }]
}

This is how I populate the dropdown menu using jquery.

$(document).ready(function() {
    $.getJSON("../cars.json", function(obj) {
        $.each(obj.cars, function(key, value) {
            $("#dropDownCars").append("<option>" + value.carsName + "</option>");
        });
    });
});

Any working example in jfiddle, would be very much appreciated! Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this piece of code....jsfiddle it explains where to put the code to select image based on the selected drop down id

Html code

 <select id="dropDownDest">
</select>

jQuery document.ready code

 var a = {
            Cars: [{
                "CarType": "BMW",
                "carID": "bmw123"
            }, {
                "CarType": "mercedes",
                "carID": "merc123"
            }, {
                "CarType": "volvo",
                "carID": "vol123r"
            }, {
                "CarType": "ford",
                "carID": "ford123"
            }]
        };
        $.each(a.Cars, function (key, value) {
            $("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
        });

        $('#dropDownDest').change(function () {
            alert($(this).val());
            //Code to select image based on selected car id
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...