Set HTML dropdown selected option using JSTL

前端 未结 3 1835
你的背包
你的背包 2020-12-24 03:50

In the same context i have another query


                        
    
提交评论

  • 2020-12-24 04:25

    Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

    <select name="foo" id="foo" value="${myBean.foo}">
        <option value="">ALL</option>
        <c:forEach items="${fooList}" var="val"> 
            <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
        </c:forEach>                     
    </select>
    
    0 讨论(0)
  • 2020-12-24 04:30

    In Servlet do:

    String selectedRole = "rat"; // Or "cat" or whatever you'd like.
    request.setAttribute("selectedRole", selectedRole);
    

    Then in JSP do:

    <select name="roleName">
        <c:forEach items="${roleNames}" var="role">
            <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
        </c:forEach>
    </select>
    

    It will print the selected attribute of the HTML <option> element so that you end up like:

    <select name="roleName">
        <option value="cat">cat</option>
        <option value="rat" selected>rat</option>
        <option value="unicorn">unicorn</option>
    </select>
    

    Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

    0 讨论(0)
  • 提交回复
    热议问题