JSP custom tag implementation multi-select drop-down box

Source: Internet
Author: User
Tags tld

A multi-choice drop-down box is used in the project. I am too lazy to search for it online. I tried to write a simple drop-down box and paste it for my reference.

 

This section of JS controls various events (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);   });}

Label type:

Public class MultiSelectTaglib extends TagSupport {// data in the drop-down box, initialize the data private List <LabelValueBean> items; // name parameter, and upload it to the background name private String nameParams; // id parameter, id private String idParams uploaded to the background; // the value of the current id, which is mainly used to re-select the checkbox private String curIdVal before the query after the query; // style, set the text box style private String textStyle; // whether it is read-only (Optional). Set the read-only attribute of the text box. The default value is read-only private boolean readonly = true; // whether a magnifier is required (optional) and whether a magnifier icon exists, the default magnifier icon is private boolean hasSele. CtImg = true; // whether the clear icon is required (Optional). You can set whether the clear icon exists. The clear icon private boolean hasClearImg = true by default. // (optional) the height of the drop-down box ), after the height is set, the private String selectHeight; // The width of the drop-down box is displayed (Optional). After the width is set, the drop-down box is displayed when the height is exceeded. The default value is 200px private String selectWidth; // whether full selection is required (optional) private boolean hasAllSelector; // The private final String SELECT_ALL = "select_all"; private final String RESOURCE_NAME = "ssb_application_resource "; /*** override doStartTag */ Public int doStartTag () {// obtain the resource file 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 ("Multi-select drop-down box label exception:" + e. getMessage () ;}} return SKIP_BODY;}/*** multi-choice box field * @ return */private String getContentString (Map <String, String> messages) {// string for storing HTML content StringBuffer contentStr = new StringBuffer (); // if the width is not set, the default value is 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 you need to set the text box to read-only if (readonly) {contentStr. append ("readonly = \" readonly \ ");} // default text box style 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 (" "); */contentStr. append ("<div style = \" display: none; position: absolute; "); // if the height of the drop-down box is set to if (StringHelper. isNotEmpty (selectHeight) {contentStr. append ("overflow: auto; height:" + selectHeight + ";") ;}contentstr. append ("width:" + selectWidth + ";"); contentStr. append ("\"> "); contentStr. append ("<table cellspacing = \" 1 \ "class = \" tb_datalist \ "> ");/ /If the list is not empty, a drop-down list if (items. isEmpty () {contentStr. append ("<tr> <td> </tr>");} else {// if you need to select all functions 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. app End ("</tr>") ;}// generate a drop-down list 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 file (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>

 

Import the tld file, JS file, and jQuery package during use:

<% @ 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>

Usage:

<MSelect: multiSelect nameParams = "con. unitName" items = "$ {dpgReportForm. operateUnitList }"
CurIdVal = "$ {dpgReportForm. con. unitName}" idParams = "con. unitName"
Hasclearimg = "true" selectheight = "200px" hasallselector = "true"/>

 

Effect:

 

If you want to customize the drop-down box style mentioned in the comment and set the selection box to the top, you can define two additional Divs, one with the select button and the other with the selected data.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.