Spring MVC:根据另一个填充下拉列表

时间:2021-02-03 07:41:26

标签: spring spring-mvc

这个枚举是在我的一个班级中定义的


public enum Type {
        TEXT(1), BINARY(2);

        private final int type;

        AttributeType(int type) {
            this.type = type;
        }

        public int getType() {
            return type;
        }
    }

下拉菜单#1

<label class="col-sm-3 col-md-3 col-lg-3 control-label"
    style="font-weight: bold; font-size: 12px; color: #666666">
    <span style="color: red;">*</span>&nbsp;Type
</label>
<div class="col-sm-9 col-md-9 col-lg-9">
    <form:select class="form-control"
        style="width: 80%" path="">
        <form:option value="" selected="true" disabled="true"
            label="Select a type" />
        <c:forEach var="attribute" items="${Type}">                                                                 
            <form:option value="${attribute}" />
        </c:forEach>
    </form:select>
    <form:label class="error" id="errorStatus" path=""
        style="color: red;">${errorStatus}</form:label>
</div>

下拉菜单#2

<label class="col-sm-3 col-md-3 col-lg-3 control-label"
    style="font-weight: bold; font-size: 12px; color: #666666">
    <span style="color: red;">*</span>&nbsp;Constraint
</label>
<div class="col-sm-9 col-md-9 col-lg-9">
    <form:select class="form-control" style="width: 80%" path="">
        <form:option value="" selected="true" disabled="true"
            label="Select a Constrait" />
            <c:forEach var="type" items="${Type}">
                <c:if test="{type== TEXT}">
                    <form:option value="" label="test1" />
                </c:if>
                <c:if test="{type== BINARY}">
                    <form:option value="" label="test2" />
                </c:if>
            </c:forEach>
        
    </form:select>
    <form:label class="error" id="errorConstraint" path=""
        style="color: red;">${errorStatus}</form:label>
</div>

在我的 Controller 类中,我已将列表添加到我的属性 model.addAttribute("TypeValue", Arrays.asList(Type.values()));

我想做什么:

如果用户在下拉菜单 #1 中选择了文本,则下拉菜单 #2 将显示 test1 和 如果用户在下拉菜单 #1 中选择了 BINARY,则显示 test2

实际结果

在下拉菜单 #1 中选择任一选项后没有显示任何内容

1 个答案:

答案 0 :(得分:0)

使用 jquery

var diction = {
  TEXT: ["B1", "B2", "B3"],
  BINARY: ["B4", "B5", "B6"]
}

// bind change event handler
$('#EventId').change(function() {
  // get the second dropdown
  $('#SecondDropdown').html(
      // get array by the selected value
      diction[this.value]
      // iterate  and generate options
      .map(function(v) {
        // generate options with the array element
        return $('<option/>', {
          value: v,
          text: v
        })
      })
    )
    // trigger change event to generate second select tag initially
}).change()

然后我删除了所有的 标签。此解决方案基于此 post

我也愿意改进我的代码