JSP自訂標籤實現多選下拉框

來源:互聯網
上載者:User

項目裡用到了一個多選下拉框,懶得在網上找,自己試著寫了個簡單的先用著,貼出來給學習的童鞋參考下。

 

這段JS控制各種事件(multiSelect.js)

/*** created by yuandong* created date 2012-5-23* last updated date 2012-6-8*/jQuery(document).ready(function(){    //Click event of select div    $('.multiSelectDiv').click(function(e){        var text = $(this).find('input[type=text]');    var hidden = $(this).find('input[type=hidden]');    var target = $(e.target);         //If target is text    if(target.attr('type') == text.attr('type'))    {        //Hide other div        $('.multiSelectDiv').find('div').each(function(){        $(this).animate({opacity: 'hide'}, 300);    });        var div = $(this).find('div');    var offSet = text.offset();    var left = offSet.left;    var top = offSet.top;        if(div.is(":visible"))    {        div.animate({opacity: 'hide'}, 300);    }    else    {       div.css({"top":top+20,"left":left}).animate({opacity:'show'}, 300);    }    }    //If target is checkbox    else if(target.attr('type') == 'checkbox')    {        var textVal = '';        var hiddenVal = '';        var selectDivObj = $(this);        var curCheckboxCount = 0;            var selectedCheckboxCount = 0;        //Get value by selected checkbox    $(this).find('input[type=checkbox][class!=selectAll]').each(function(){            if($(this).is(':checked'))    {        textVal += $(this).parent().parent().find('span').text() + ',';        hiddenVal += $(this).val() + ',';        selectedCheckboxCount++;    }    //When exist checkbox not select,set 'select all' to not select     else    {        selectDivObj.find('input[type=checkbox][class=selectAll]').attr('checked','');    }    curCheckboxCount++;    });        if(curCheckboxCount>0 && selectedCheckboxCount>0 && curCheckboxCount==selectedCheckboxCount)        {           selectDivObj.find('input[type=checkbox][class=selectAll]').attr('checked','true');        }        text.val(textVal.substring(0,textVal.length-1));    hidden.val(hiddenVal.substring(0,hiddenVal.length-1));    }    //If target is clearImg, clear text,hidden,and checkbox value    else if($(this).find('img').length>0  && target.attr('name') == 'clearImg')    {        text.val('');    hidden.val('');    $(this).find('input[type=checkbox]').each(function(){       if($(this).is(":checked"))       {     $(this).attr("checked",'');       }    });    }    //If target is selectImg, show select    else if($(this).find('img').length>0  && target.attr('name') == 'selectImg')    {        text.click();    }    });        //Hide div when user click other area    $('html').click(function(e){    //If not multi select div area, return     if($(e.target).isChildAndSelfOf (".multiSelectDiv"))    {        return;    }    //Else hide select div    else    {    $('.multiSelectDiv').find('div').each(function(){        $(this).animate({opacity: 'hide'}, 300);    });    }    });         //Select all items    $('.selectAll').click(function(e){        var all = $(this);        all.parent().parent().parent().find('input[type=checkbox]').each(function(){           if(all.is(":checked"))           {               $(this).attr("checked",'true');           }           else           {               $(this).attr("checked",'');           }        });    });           //Check current elements     jQuery.fn.isChildAndSelfOf = function(b){         return (this.closest(b).length > 0);     };        //On init    initMultiSelect();    });//Init selectfunction initMultiSelect(){   $('.multiSelectDiv').each(function(){       var hiddenVal = $(this).find('input[type=hidden]').val();       var textVal = '';       var curCheckboxCount = 0;       var selectedCheckboxCount = 0;       var selectDivObj = $(this);       //Select checkBox and set up input value after do query       if(hiddenVal != '')       {       $(this).find('input[type=checkbox][class!=selectAll]').each(function(){    if(hiddenVal.indexOf($(this).val()) != -1)    {        $(this).attr('checked',true);        textVal += $(this).parent().parent().find('span').text() + ',';        selectedCheckboxCount ++;    }    curCheckboxCount ++;       });       $(this).find('input[type=text]').val(textVal.substring(0,textVal.length-1));       //If checkbox count of current select is equals selected checkbox count,checked 'select all'        if(curCheckboxCount>0 && selectedCheckboxCount>0 && curCheckboxCount==selectedCheckboxCount)       {           selectDivObj.find('input[type=checkbox][class=selectAll]').attr('checked','true');       }       }              //Set up the width of the select div       var textWidth = 0;       var img1Width = 0;       var img2Width = 0;              var textObj = $(this).find('input[type=text]');       textWidth = textObj.width();              var img1Obj = $(this).find('img');       var tempImgObj = new Image();        tempImgObj.src = img1Obj.attr( 'src');       img1Width = tempImgObj.width;              var img2Obj = img1Obj.next('img');       tempImgObj.src = img2Obj.attr( 'src');       img2Width = tempImgObj.width;              $(this).width(textWidth + img1Width + img2Width + 10);   });}

標籤類:

public class MultiSelectTaglib extends TagSupport {    //下拉框資料,初始化下拉框的資料    private List<LabelValueBean> items;    //名稱參數,傳到背景名稱    private String nameParams;    //id參數,傳到背景id    private String idParams;    //當前id的值,主要用於查詢後再次選中查詢前的checkbox    private String curIdVal;    //樣式,設定文字框樣式    private String textStyle;    //是否唯讀(可選),設定文字框唯讀屬性,預設唯讀    private boolean readonly = true;    //是否需要放大鏡(可選),設定是否有放大鏡表徵圖,預設有放大鏡表徵圖    private boolean hasSelectImg = true;    //是否需要清空表徵圖(可選),設定是否有清空表徵圖,預設有清空表徵圖    private boolean hasClearImg = true;    //下拉框高度(可選),設定高度後,超過高度後會顯示下拉框    private String selectHeight;     //下拉框寬度(可選),設定寬度後,超過高度後會顯示下拉框,預設200px    private String selectWidth;    //是否需要全選功能(可選)    private boolean hasAllSelector;        //國際化用到的參數    private final String SELECT_ALL = "select_all";    private final String RESOURCE_NAME = "ssb_application_resource";    /**     * 重寫doStartTag     */    public int doStartTag()     {                //得到資源檔        Locale locale =  pageContext.getRequest().getLocale();        ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_NAME, locale);        Map<String, String> messages = new HashMap<String, String>();        messages.put(SELECT_ALL, bundle.getString("multiSelect.selectAll"));                JspWriter out = pageContext.getOut();                if (out != null)         {            try             {                    out.print(getContentString(messages));            } catch (IOException e)             {                                PPMLog.debug("多選下拉框標籤異常: " + e.getMessage());            }        }        return SKIP_BODY;    }        /**     * 拼接顯示的多選框域     * @return     */    private String getContentString(Map<String, String> messages)    {        //使用者存放HTML內容串        StringBuffer contentStr = new StringBuffer() ;       //如果沒設定寬度,預設200px        if(StringHelper.isEmpty(selectWidth))        {            selectWidth = "200px";        }                //contentStr.append("<div class=\"multiSelectDiv\" style=\"width:" + selectWidth + "\">")        contentStr.append("<div class=\"multiSelectDiv\">")                  .append("<input type=\"text\" name=\"").append(nameParams).append("\"");        //如果需要把文字框設定為唯讀        if(readonly)        {            contentStr.append("readonly=\"readonly\"");        }        //文字框預設樣式        String textDefStyle = "width:200px";        contentStr.append(" style=\"").append(StringHelper.isEmpty(textStyle) ? textDefStyle : textStyle).append("\"/>")                  .append("<input type=\"hidden\" name=\"").append(idParams).append("\" value=\"" + curIdVal + "\"/>");                HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();        if(hasSelectImg)        {            String imgPath = request.getContextPath() + "/images/projectinfo/search.gif";            contentStr.append("<img src=\"" + imgPath + "\" class=\"icon\" style=\"cursor:pointer\" name=\"selectImg\"/>");        }        //如果需要清除表徵圖        if(hasClearImg)        {            String imgPath = request.getContextPath() + "/images/clear.gif";                        contentStr.append("<img src=\"" + imgPath + "\" class=\"icon\" style=\"cursor:pointer\" name=\"clearImg\"/>");        }                /*         * 如果以後要支援自訂其他樣式,可以將這裡的高度和寬度去掉, 直接自訂下拉框的樣式,         * 注意這裡預設的"display:none;position: absolute;"是必需的樣式,如果自訂裡有同樣屬性定義,會直接覆蓋同名屬性的值.         * 這裡為了使用簡便,暫時不支援         String selectDefStyle = "display:none;position: absolute;";                 contentStr.append(" style=\"").append(StringHelper.isEmpty(selectStyle) ? selectDefStyle+selectStyle : selectStyle).append("\"/>");        */                contentStr.append("<div style=\"display:none;position: absolute;");         //如果設定了下拉框高度        if(StringHelper.isNotEmpty(selectHeight))        {            contentStr.append("overflow:auto;height:" + selectHeight + ";");        }                contentStr.append("width:" + selectWidth + ";");        contentStr.append("\">");        contentStr.append("   <table  cellspacing=\"1\" class=\"tb_datalist\">");        //如果list不為空白,產生下拉式清單        if(items.isEmpty())        {            contentStr.append("<tr><td><td></tr>");        }        else        {            //如果需要全選功能            if(hasAllSelector)            {                contentStr.append("<tr class=\"tr_title\">");                contentStr.append("<td width=\"10%\">")                .append("   <input class=\"selectAll\" value=\"\" type=\"checkbox\"/></td>");                contentStr.append("<td width=\"90%\"><span>").append(messages.get(SELECT_ALL)).append("</span></td>");                contentStr.append("</tr>");            }            //產生下拉式清單            for(LabelValueBean labelVal:items)            {                if(labelVal != null)                {                    contentStr.append("<tr>");                    contentStr.append("<td width=\"10%\">")                    .append("   <input type=\"checkbox\"  value=\"" + labelVal .getValue()+ "\"/></td>");                    contentStr.append("<td width=\"90%\">").append("<span>" + labelVal.getLabel() + "</span></td>");                    contentStr.append("</tr>");                }            }        }        contentStr.append("</table>");        contentStr.append("</div>");        contentStr.append("</div>");                        return contentStr.toString() ;    }    public void release() {        super.release();    }    public void setNameParams(String nameParams)    {        this.nameParams = nameParams;    }    public void setStyle(String textStyle)    {        this.textStyle = textStyle;    }    public void setIdParams(String idParams)    {        this.idParams = idParams;    }    public void setCurIdVal(String curIdVal)    {        this.curIdVal = curIdVal;    }    public void setItems(List<LabelValueBean> items)    {        this.items = items;    }    public void setHasClearImg(Boolean hasClearImg)    {        this.hasClearImg = hasClearImg;    }    public void setSelectWidth(String selectWidth)    {        this.selectWidth = selectWidth;    }    public void setSelectHeight(String selectHeight)    {        this.selectHeight = selectHeight;    }    public void setHasAllSelector(boolean hasAllSelector)    {        this.hasAllSelector = hasAllSelector;    }    }

tld檔案(multiSelect.tld):

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"><taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><shortname>multiSelectTaglib</shortname><uri>/multiSelectTaglib</uri><tag><name>multiSelect</name><tagclass>com.zte.ppm.baseutil.business.multiSelectTaglib.service.MultiSelectTaglib</tagclass><bodycontent>JSP</bodycontent><info>check if the user have the right access</info><attribute><name>items</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>curIdVal</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>idParams</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>nameParams</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>textStyle</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>readonly</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>hasSelectImg</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>hasClearImg</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>selectHeight</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>selectWidth</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>hasAllSelector</name><required>false</required><rtexprvalue>true</rtexprvalue></attribute></tag></taglib>

 

使用時匯入相應tld檔案和JS檔案以及jQuery包:

<%@ taglib uri="/WEB-INF/multiSelect.tld" prefix="mSelect"%>

<script type="text/javascript" src="${appRoot}/js/multiSelect.js"></script>

<script type="text/javascript" src="${appRoot}/js/jquery/jquery-1.4.2.min.js"></script>

使用方法:

<mSelect:multiSelect nameParams="con.unitName" items="${dpgReportForm.operateUnitList}"
                  curIdVal="${dpgReportForm.con.unitName}" idParams="con.unitName"
                  hasClearImg="true" selectHeight="200px" hasAllSelector="true"/>

 

效果:

 

如果要實現注釋中說的自訂下拉框樣式且將全選選擇框置頂,可以另外定義兩個div,一個放全選按鈕,一個放下面的選擇資料。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.