【问题标题】:Struts <html:select> set selected option dynamicallyStruts <html:select> 动态设置选中的选项
【发布时间】:2015-05-06 10:14:02
【问题描述】:

在下面的 Struts 标记代码中,我需要在根据从操作传递的值呈现页面之前更改选择中的选定值。但是我找不到获取选项值并对其进行操作的方法。

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

<html:form action="searchMusic" method="POST">
   <html:select property="searchType">
      <html:option value="CLASSICAL">CLASSICAL</html:option>
      <html:option value="ROCK">ROCK</html:option>
   </html:select>
   <html:submit value="Search"/>
</html:form>

我尝试了以下功能,但它不起作用。

$(document).ready(function() {

    var viewRockOrClassical = '${viewRockOrClassical}';
    if (!isEmpty(viewRockOrClassical)) {
        var searchBy = document.getElementByName("searchType");
        if (viewRockOrClassical == "ROCK") {
            searchBy.value = "ROCK";
        }

    }

});

function isEmpty(str) {
    return (!str || 0 === str.length);
}

我在页面加载时遇到的错误是

Uncaught TypeError: undefined is not a function

这是由 "document.getElementByName("searchType")" 行引起的。

【问题讨论】:

    标签: jsp struct jsp-tags taglib


    【解决方案1】:

    动态设置 Struts 表单中的值。我们可以直接将值设置为关联的Struts动作表单,并转发到包含该表单的JSP页面。

    public ActionForward selectMusic(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        Object requestForMusicType = request.getParameter("requestForMusicType");
    
        if (requestForMusicType != null && "forRockMusic".equalsIgnoreCase((String) requestForMusicType)) {
            MusicTypeSearchForm musicTypeSearchForm = new MusicTypeSearchForm();
            musicTypeSearchForm.setSearchType("ROCK");
            request.setAttribute("musicTypeSearchForm", musicTypeSearchForm);
        }
    
        return mapping.findForward("searchForMusic");
    }
    

    【讨论】:

      【解决方案2】:

      在动作类中设置属性值,因为您在动作本身中拥有值。

      formObject.searchType = value;
      

      因此它将在页面加载时显示所选值。

      【讨论】:

      • 是的。有用。谢谢。必须将表单对象设置为请求。我会用代码发布答案。
      【解决方案3】:

      给选择标签一个 id="selectbox" 并试试这个:

       var viewRockOrClassical = '${viewRockOrClassical}';
              if (!isEmpty(viewRockOrClassical)) {
                  var searchBy = document.getElementByID("searchType").options;
                  for(int i=0;i<searchBy.length;i++) {
                      if (viewRockOrClassical == "ROCK") {
                          searchBy[i].value = "ROCK";
                      }
                  }   
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        相关资源
        最近更新 更多