使用字符串映射创建动态下拉菜单

时间:2015-09-21 11:15:47

标签: javascript jquery html drop-down-menu

html看起来像

<div class="col-xs-12 col-sm-3 col-md-3">
    <label>Status</label>
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
    <div class="input-group">
	    <div class="input-group-addon">
		    <i class="fa fa-filter"></i>
	    </div>
						
	    <select class="form-control pull-right" name="status" id="status" tabindex="2">
		<option value="1">Enable</option>
                <option value="0">Disable</option>
            </select>
        
            <select class="form-control pull-right" name="status_reason" id="status_reason" tabindex="2">
	         <option value=""></option>
	         <option value=""></option>
                 <option value=""></option>
	         <option value=""></option>
            </select>
						
    </div><!-- /.input group -->

用户从启用或禁用状态下拉框中选择状态后,应显示另一个下拉列表(即status_reason下拉列表),具体取决于状态下拉列表的选择。动态值将存储在包含字符串作为键和值的映射中。

1 个答案:

答案 0 :(得分:0)

你需要这样的东西吗?现在我已对地图值进行了硬编码,但您可以使用自己的源分配这些变量。

$(document).ready(function(){
  
  var map0 = new Object(); // or var map = {};
  map0["value0_0"] = "reason0_0";
  map0["value0_1"] = "reason0_1";
  map0["value0_2"] = "reason0_2";

  var map1 = new Object(); // or var map = {};
  map1["value1_0"] = "reason1_0";
  map1["value1_1"] = "reason1_1";
  map1["value1_2"] = "reason1_2";

  var reasons = [map0, map1];

  $("#status").change(function(){
  
    $("#status_reason").empty();
  
    var selected_status = $(this).val();
    var reason_value_map = reasons[parseInt(selected_status)]

    for(var k in reason_value_map) 
    {
      $("#status_reason").append('<option   value="'+k+'">'+reason_value_map[k]+'</option>');
    }
  
  
  });
  
  $("#status").change(); //populate the second DD on document ready
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12 col-sm-3 col-md-3">
    <label>Status</label>
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
    <div class="input-group">
	    <div class="input-group-addon">
		    <i class="fa fa-filter"></i>
	    </div>
						
	    <select class="form-control pull-right" name="status" id="status" tabindex="2">
		<option value="1">Enable</option>
                <option value="0">Disable</option>
            </select>
        
            <select class="form-control pull-right" name="status_reason" id="status_reason" tabindex="2">
	         <option value=""></option>
	         <option value=""></option>
                 <option value=""></option>
	         <option value=""></option>
            </select>
						
    </div><!-- /.input group -->