使用数组填充动态下拉列表

时间:2018-07-10 13:21:41

标签: php jquery

我正在尝试使用多维数组在PHP中进行动态下拉菜单。

我的第一个选择框正确填充,但是在选择建筑物时,我需要第二个选择框来显示相应的显示(大厅,休息室等)

这是数组:

$displays = array(
  "Company" => array(
    "Building 1"=>array(
      "Displays"=>array(
        "Lobby",
        "Break Room",
        "Office",
        ),
      ),
    "Building 2"=>array(
      "Displays"=>array(
        "Break Room",
        "Office",
        ),
      ),
    "Building 3"=>array(
      "Displays"=>array(
        "Lobby",
        "Break Room",
        ),
      ),
    "Building 4"=>array(
      "Displays"=>array(
        "Lobby",
        "Break Room",
        "Office"
      ),
    ),
  ),
);

还有我目前的两个选择框:

/*This select option works to fill the list with building 1 through building 4, as it should*/
<select class="form-control" id="plantSelect">
    <?php foreach($displays["Company"] as $area_name => $area_details): ;?>
    <option><?php echo $area_name ?></option>
    <?php endforeach ?>
</select>

/*I need this one to show the displays (lobby, break room, office, etc.) for each builing as it's selected*/
<select class="form-control" id="areaSelect">
    <?php foreach($displays["Company"] as $area_name => $area_details): ;?>
    <option><?php echo $area_details?></option>
    <?php endforeach ?>
</select>

还有我不完整的jquery:

 <script type="text/javascript">
    $("#plantSelect").change(function() {
     $("#areaSelect").load("/*don't know what to put here*/" + $("#plantSelect").val());
    });
</script>

非常感谢您完成此工作

1 个答案:

答案 0 :(得分:2)

json_encode数组并将其作为JS对象存在于页面中

var Company = {
  "Building 1": [{
    "Displays": [
      "Lobby",
      "Break Room",
      "Office"
    ]
  }],
  "Building 2": [{
    "Displays": [
      "Break Room",
      "Office"
    ]
  }],
  "Building 3": [{
    "Displays": [
      "Lobby",
      "Break Room"
    ]
  }],
  "Building 4": [{
    "Displays": [
      "Lobby",
      "Break Room",
      "Office"
    ]
  }]
};

$.each(Company, function(bld) {
  $("#plantSelect").append('<option value="' + bld + '">' + bld + '</option>')
});
$("#plantSelect").on("change", function() {
  $("#areaSelect")[0].length=1;
  if (this.value) {
    $.each(Company[this.value][0].Displays,function(_,disp) {
      $("#areaSelect").append('<option value="' + disp + '">' + disp + '</option>')
    });
  }  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="plantSelect">
  <option value="">Please select</option>
</select>

<select class="form-control" id="areaSelect">
  <option value="">Please select</option>
</select>