Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill dropdown list with json

I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?

This is example of my JSON, can be much longer.

[
    {
        "id": "1",
        "name": "test"
    },
    {
        "id": "1",
        "name": "test"
    }
]
like image 388
Tara Avatar asked Dec 04 '22 08:12

Tara


1 Answers

HTML:

<select id="sel">

</select>

JavaScript:

$(function() {
    var data = [
        {
        "id": "1",
        "name": "test1"},
    {
        "id": "2",
        "name": "test2"}
    ];
    $.each(data, function(i, option) {
        $('#sel').append($('<option/>').attr("value", option.id).text(option.name));
    });
})

Here's a working example. http://jsfiddle.net/ms2Ma/

like image 154
Ashish Avatar answered Dec 09 '22 16:12

Ashish