Home Web Front-end JS Tutorial jquery infinite cascading drop-down menu simple example demonstration_jquery

jquery infinite cascading drop-down menu simple example demonstration_jquery

May 16, 2016 pm 03:30 PM

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);

Copy after login

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>
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles