显示来自json的下拉值

时间:2016-07-19 07:19:31

标签: jquery html json

我是html:

<div id="div_bahan" class="form-group div_bahan">
  <label for="images" class="col-md-3 control-label">Bahan</label>
  <div class="col-md-4" id="col_bahan">
    <select name="bahan[]" id="bahan" class="form-control">
      <option value="0">--pilih--</option>
      <?php
        $qry = $db->query("SELECT * FROM bahan");
        while ($bahan = $qry->fetch_array()) {
          $qry2 = $db->query("SELECT * FROM warna WHERE id_warna='$bahan[id_warna]'");
          $warna = $qry2->fetch_array();
      ?>
      <option value="<?php echo $bahan['id_bahan']; ?>"><?php echo $bahan['id_bahan']; ?> - <?php echo $bahan['nm_bahan'] . ' Warna ' . $warna['nm_warna']; ?></option> 
      <?php
        }
      ?>
    </select>
  </div>
  <div class="col-md-2 addbahan" id="addbahan">
    <b onclick="addBahan()"  class="btn btn-success btn-sm btn-flat"><span class="glyphicon glyphicon-plus"></span>Tambah bahan</b>
  </div>
</div>

当我编辑动作时,html从json获取数据。

这个json:

{
  "bahan": [{
    "id_bahan": "4",
    "nm_jenis": "katun",
    "nm_warna": "merah",
    "nm_bahan": "Bhn Jeans 04",
    "stok_bahan": "5",
    "no": 1
  }, {
    "id_bahan": "1",
    "nm_jenis": "katun",
    "nm_warna": "merah",
    "nm_bahan": "Bhn Gamis 01",
    "stok_bahan": "21",
    "no": 2
  }, {
    "id_bahan": "3",
    "nm_jenis": "katun",
    "nm_warna": "hijau",
    "nm_bahan": "Bhn Jaket 02",
    "stok_bahan": "12",
    "no": 3
  }, {
    "id_bahan": "2",
    "nm_jenis": "spandex",
    "nm_warna": "kuning",
    "nm_bahan": "Bhn koko 01",
    "stok_bahan": "3",
    "no": 4
  }]
}

如何编辑操作并在select value中显示数据?

1 个答案:

答案 0 :(得分:0)

使用此选项可向select元素添加选项标记:

$(data.bahan).each(function(i, e) {
    var name = e.id_bahan+' - '+e.nm_bahan+' Warna '+e.nm_warna,
        o = new Option(name, e.id_bahan);

    $('#bahan').append(o);
});