web-dev-qa-db-ja.com

JSTLを使用してHTMLドロップダウン選択オプションを設定する

同じコンテキストで別のクエリがあります

<select multiple="multiple" name="prodSKUs">
            <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
          <option value="${productSubCategoryList}"${productSubCategoryList == productSubCategoryName ? 'selected' : ''}>${productSubCategoryList}</option>
         </c:forEach>
        </select>

リクエストの対応する設定は

for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    request.setAttribute("productSubCategoryName",productSubCategoryName);

}

ここで、2つのforから戻り値を取得しても、複数の選択ドロップダウンがあり、UIでは2番目ではなく1つのデータのみが強調表示されますが、コードの何が問題になっていますか?

21
sarah

コンボに入れる要素のコレクション$ {roles}があり、選択した要素を$ {selected}持っていると仮定すると、次のようになります。

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

更新(次の質問)

属性「productSubCategoryName」を上書きしています。 forループの最後で、最後のproductSubCategoryName。

式言語の制限のため、これに対処する最良の方法はマップを使用することだと思います。

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

そして、JSPで:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>
29
Maurice Perry

サーブレットで:

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

次に、JSPで以下を行います。

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

HTMLのselected属性を印刷します<option>要素を使用すると、次のようになります。

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

問題は別として、これはnotコンボボックスです。これはドロップダウンです。コンボボックスは編集可能ドロップダウンです。

10
BalusC

本当にシンプル。正しいオプションに文字列「選択」を追加するだけです。次のコードでは、$ {myBean.foo == val? 'selected': ''}は、オプションの値がBean値と同じ場合、文字列 'selected'を追加します。

<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>
3
MattC