Write your own jquery plugin's infinite cascade drop-down box

Source: Internet
Author: User

Because it is cascading, the data must be tree-structured, and I have the following test data:

Look under:

1.> Chart One:

2.> Figure II:

3.> Figure III:

From the figure, the number of drop-down boxes is not written dead, but dynamically loaded. Whenever the drop-down box chooses to change, an AJAX request is sent, the request successfully returns the JSON-formatted data, and when the returned data is not empty (that is, when there are child nodes), a drop-down box is added to the page, and no is added.

The implementation code for the plugin is as follows:

(function($) {$.fn. Cascadingselect=function(options) {//Default parameter Settings        varSettings ={URL:"/handler.ashx",//Request PathData: "0",//initial value (string format)Split: ",",//SeparatorCssname: "Select",//Style nameVal: "id",//<option value= "id" >name</option>Text: "Name",//<option value= "id" >name</option>Hiddenname: "Selval"//hides the value of the domain's Name property        }        //Merging Parameters        if(Options) $.extend (settings, options); //Chain Principle        return  This. each (function() {init ($ ( This), settings.data); /*initializes @param container container object @param data Initial value*/            functioninit (container, data) {//Create a hidden Field object and assign an initial value                var_input = $ ("<input type= ' hidden ' name= '" + settings.hiddenname + "'/>"). AppendTo (Container). val (Settings.data); vararr =Data.split (Settings.split);  for(vari = 0; i < arr.length; i++) {                    //Create drop-down boxCreateselect (container, arr[i], Arr[i + 1] | |-1); }            }            /*Create drop-down box @param container container object @param parentid Parent ID number @param ID Self ID number*/            functionCreateselect (container, ParentID, id) {//creates a Select object and puts the select object inside the container                var_select = $ ("<select></select>"). AppendTo (Container). addclass (Settings.cssname); //If ParentID is empty, the _parentid value is 0                var_parentid = ParentID | | 0; //To send an AJAX request, the returned data must be in JSON format$.getjson (Settings.url, {parentid: _parentid},function(data) {//Add child nodes <option>AddOptions (container, _select, data). val (id | |-1)                }); }            /*Add <option> child nodes @param container container object @param Select drop-Down box object for the drop-down box @param data child nodes (requires data in JSON format)*/            functionaddoptions (container, select, data) {Select.append ($ (' <option value= '-1 ">= Please select =</option> '));  for(vari = 0; i < data.length; i++) {select.append ($ (' <option value= ' + data[i][settings.val ' + ' > ' + data[i][settings.text] + ' </option> ')); }                //bind a Change event for selectSelect.bind ("Change",function() {_onchange (container, $ ( This), $( This). Val ())}); returnSelect; }            /*the Change event function for select @param the Container container object @param the Select drop-down box object @par The value of the AM ID current drop-down box*/            function_onchange (container, select, id) {varNextall = Select.nextall ("select"); //if the value of the current select object is empty or-1 (that is, = = = =), remove all subsequent Select Objects                if(!id | | id = = "-1") {nextall.remove (); } $.getjson (Settings.url, {parentid:id},function(data) {if(Data.length > 0) {                        var_html = $ ("<select class=" + settings.cssname + "></select>"); var_select =addoptions (container, _html, data); //determines whether a select object is followed by the current select object                        if(Nextall.length < 1) {select.after (_select);//No, add it directly                        } Else{nextall.remove ();//first Remove and then addSelect.after (_select); }                    }                    Else{nextall.remove ();//No subkeys are removed from the subsequent select}
            Saveval (container); // for data saving, this method must be placed inside the callback function });
         // saveval (container); // if placed here, a bug will appear
} /*saves the selected value in a hidden field for form submission Save @param container container object*/ functionSaveval (container) {vararr =NewArray (); Arr.push (0);//An array of arr adds element 0, and the parent node starts from 0, so add 0 $("Select", Container). each (function () { if($( This). Val () > 0) {Arr.push ($ ( This). Val ());//gets the value of each Select object under container and adds it to the array arr } }); //Assigning values to hidden Field objects$ ("input[name=" + Settings.hiddenname + "']", Container). Val (Arr.join (Settings.split)); } }); }}) (JQuery);

Note I have tried to write the details, but still have to do some things to explain.

1.> My background language is in C #, so you see a request path like this (URL: "/handler.ashx"), you have no problem with other languages, but the data returned through an AJAX request must be data in JSON format.

  

2.> in Initialization method init (), we put a hidden field in the container that is used to store the value, and we assign it by a saveval() method. The reason to hide the domain is because the data we choose is ultimately saved to the database, so there will be a form submission operation, so add a hidden field.

  

3.> the split separator in default parameter settings (settings). Here is a comma (,) you can also use other, such as (-) or (|). It is primarily used to split and combine the values of all drop-down boxes.

The split is primarily when initializing (init), such as when you give the initial value (data) is not 0, but 0,1,4 it is then split it, one after the creation of a drop-down box method Createselect ()

The combination is mainly when assigning values to hidden fields, using a delimiter to stitch the values of each drop-down box into a single string and then assigning it to the hidden field.

4.> default parameter setting (settings) inside {val: "id", Text: "Name"}. They correspond to the corresponding property names in the JSON object that you return.

5.> in the _onchange () method has the problem of writing to the Saveval () execution position. There is a bug written out of the callback function because $.getjson () is asynchronous by default and executes the Saveval () method when the callback method has not finished executing. Let's see where the bug is:

  

  

The value of the hidden field at this time is wrong, and the correct value should be 0,1,5. Because the callback function is not finished, that is, nextall.remove () This is not executed, is executed saveval ()

The code for the HTML part of the demo:

<HTML><Head>    <title></title>    <styletype= "Text/css">        *{margin:0;padding:0;}#box{width:500px;margin:100px Auto;}. Select{width:120px;Height:30px;Margin-right:5px;}    </style></Head><Body>    <!--Container -    <DivID= "box"></Div>       <Scriptsrc= "Scripts/jquery-1.4.1.min.js"type= "Text/javascript"></Script>    <Scriptsrc= "Scripts/jquery.similar.cascadingselect.js"type= "Text/javascript"></Script>    <Scripttype= "Text/javascript">        $("#box"). Cascadingselect ({data:"0,1,4"}); //Set initial value to 0,1,4 </Script></Body></HTML>

Operation Result:

Backstage code here will not give, after all, not everyone uses C # ....

Write your own jquery plugin's infinite cascade drop-down box

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.