Fill dropdown list with json

前端 未结 3 1965
眼角桃花
眼角桃花 2021-01-03 05:47

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

相关标签:
3条回答
  • 2021-01-03 06:40

    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/

    0 讨论(0)
  • 2021-01-03 06:40

    Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.

    You need to follow few steps:

    • Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
    • Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.

    Here is the data:

    var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
    var Data ={"phones":[
      {
         "oid":":000000F0:00000458:",
         "level1":"3G",
         "level2":"white",
         "level3":"16GB",
         "level4":"slim",
         "level5":"Back cover",
         "level6":"headphone",
         "price":"£568.63",
         "addToCart":"#Cart1"
      },
      {
         "oid":":000000F0:000003DA:",
         "level1":"3G",
         "level2":"black",
         "level3":"16GB",
         "level4":"slim",
         "level5":"Flip cover",
         "level6":"headphone",
         "price":"£615.79",
         "addToCart":"#Cart7"
      }]};
    

    See the full working code here: https://jsfiddle.net/raju_sumit/681ppgq0/5/

    0 讨论(0)
  • 2021-01-03 06:42

    Try this :)

    Javascript:

    $.getJSON("/array.json",
      function (json) {
          $.each(json,
          function (key, value) {
          $("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
          });
    });
    
    0 讨论(0)
提交回复
热议问题