search
HomeWeb Front-endJS Tutorialjquery infinite cascading drop-down menu simple example demonstration_jquery

The examples in this article describe the code of jquery infinite cascading drop-down menu and the implementation ideas of jquery infinite cascading drop-down menu. Share it with everyone for your reference. The details are as follows:

Final rendering:

Because it is cascaded, the data must be in a tree structure. The test data here is as follows:

Look at the rendering:

1. Effect picture 1:

2. Effect picture two:

3. Effect picture three:

As can be seen from the picture, the number of drop-down boxes is not hard-coded, but dynamically loaded. Whenever the drop-down box selection changes, an ajax request will be sent, and the request will successfully return json format data. When the returned data is not empty (that is, when there are child nodes), a drop-down box will be added to the page. If not, then Not added.

The implementation code of the plug-in is as follows:

(function ($) {
 $.fn.CascadingSelect = function (options) {

  //默认参数设置
  var settings = {
   url: "/Handler.ashx", //请求路径
   data: "0",    //初始值(字符串格式)
   split: ",",    //分割符
   cssName: "select",  //样式名称
   val: "id",    //<option value="id">name</option>
   text: "name",   //<option value="id">name</option>
   hiddenName: "selVal" //隐藏域的name属性的值
  }

  //合并参数
  if (options)
   $.extend(settings, options);


  //链式原则
  return this.each(function () {

   init($(this), settings.data);

   /*
   初始化
   @param container 容器对象
   @param data   初始值
   */
   function init(container, data) {

    //创建隐藏域对象,并赋初始值
    var _input = $("<input type='hidden' name='" + settings.hiddenName + "' />").appendTo(container).val(settings.data);

    var arr = data.split(settings.split);
    for (var i = 0; i < arr.length; i++) {
     //创建下拉框
     createSelect(container, arr[i], arr[i + 1] || -1);
    }
   }


   /*
   创建下拉框
   @param container 容器对象
   @param parentid  父ID号
   @param id   自身ID号
   */
   function createSelect(container, parentid, id) {

    //创建select对象,并将select对象放入container内
    var _select = $("<select></select>").appendTo(container).addClass(settings.cssName);

    //如果parentid为空,则_parentid值为0
    var _parentid = parentid || 0;

    //发送AJAX请求,返回的data必须为json格式
    $.getJSON(settings.url, { parentid: _parentid }, function (data) {

     //添加子节点<option>
     addOptions(container, _select, data).val(id || -1)

    });
   }


   /*
   为下拉框添加<option>子节点
   @param container 容器对象
   @param select  下拉框对象
   @param data   子节点数据(要求数据为json格式)
   */
   function addOptions(container, select, data) {

    select.append($('<option value="-1">=请选择=</option>'));

    for (var i = 0; i < data.length; i++) {
     select.append($('<option value="' + data[i][settings.val] + '">' + data[i][settings.text] + '</option>'));
    }

    //为select绑定change事件
    select.bind("change", function () { _onchange(container, $(this), $(this).val()) });

    return select;
   }


   /*
   select的change事件函数
   @param container 容器对象
   @param select  下拉框对象
   @param id   当前下拉框的值
   */
   function _onchange(container, select, id) {

    var nextAll = select.nextAll("select");

    //如果当前select对象的值是空或-1(即:==请选择==),则将其后面的select对象全部移除
    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);

      //判断当前select对象后面是否跟有select对象
      if (nextAll.length < 1) {

       select.after(_select); //没有则直接添加

      } else {

       nextAll.remove(); //有则先移除再添加
       select.after(_select);
      }
     }
     else {
      nextAll.remove(); //没有子项则后面的select全部移除
     }
            saveVal(container); //进行数据保存,此方法必须放在回调函数里面
    });

         //saveVal(container); //如果放在这里,则会出现bug

   }


   /*
   将选择的值保存在隐藏域中,用于表单提交保存
   @param container 容器对象
   */
   function saveVal(container) {

    var arr = new Array();
    arr.push(0); //为数组arr添加元素0,父节点从0开始,所以添加0

    $("select", container).each(function () {
     if ($(this).val() > 0) {
      arr.push($(this).val()); //获取container下每个select对象的值,并添加到数组arr
     }
    });

    //为隐藏域对象赋值
    $("input[name='" + settings.hiddenName + "']", container).val(arr.join(settings.split));
   }

  });
 }
})(jQuery);

I have tried my best to write the notes in detail, but I still need to explain some knowledge points.

1. My background language is C#, so the request path you see is like this (url: "/Handler.ashx"), you can use other There is no problem with the language, but the data returned through the ajax request must be in json format.

 

2. In the initialization method init(), we put a hidden field into the container. This hidden field is used to store values. We assign a value to it through a saveVal() method. The reason why we need to add a hidden field is because the data we choose will eventually be saved in the database, so there will be a form submission operation, so we add a hidden field.

 

3. The split separator in the default parameter settings (settings). The comma (,) is used here. You can also use other ones, such as (-) or (|). It is mainly used to split and combine the values ​​​​of all drop-down boxes.

Splitting is mainly done during initialization (init). For example, the initial value (data) you give is not 0, but 0,1,4. At this time, it will be split and the create drop-down box method createSelect will be executed one by one. ()

Combination is mainly when assigning values ​​to hidden fields, using separators to splice the values ​​​​of each drop-down box into a string, and then assigning it to the hidden field.

4. {val: "id", text: "name" } in the default parameter settings (settings). They correspond to the corresponding attribute names in the json object you return.

5. There is a problem with writing the execution location of saveVal() in the _onchange() method. The reason why bugs occur when written outside the callback function is because $.getJSON() is asynchronous by default, and the saveVal() method is executed before the callback method is completed. Let’s take a look at where the bug is:

 

At this time, the value of the hidden field is wrong, and the correct value should be 0,1,5. Since the callback function has not been executed yet, that is, when nextAll.remove() has not been executed, saveVal()

is executed.

Code of Html part of DEMO:

<html>
<head>
 <title></title>
 <style type="text/css">
  *{margin:0;padding:0;}
  #box{ width:500px; margin:100px auto;}
  .select{ width:120px; height:30px; margin-right:5px;}
 </style>
</head>
<body>
 <!--容器-->
 <div id="box"></div> 
 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script src="Scripts/jquery.similar.cascadingselect.js" type="text/javascript"></script>
 <script type="text/javascript">
  $("#box").CascadingSelect({data:"0,1,4"}); //设置初始值为0,1,4
 </script>
</body>
</html>

The above is all the content of jquery to achieve the effect of infinite cascading drop-down menu. I hope it will be helpful to everyone's learning.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools