Skip to content Skip to sidebar Skip to footer

How To Create Multilevel Dynamic Dropdown Using Jquery

I am trying to create Multilevel Dropdown. I have default dropdown with values Ex. Parent Dropdown with Id='ddl1' If we select value from it then load data from server with selecte

Solution 1:

For creating n level dropdowns you need to create a dropdown in ajax callback like this:

 $.ajax({
    url: "Your URL",
    method: "GET",
    dataType: 'json',
    success: function (data) {
       $("Your Dropdown Conatiner").append("<select><option name="option1" value="1"></option>...</select>");
    },
    error: function (data) {

    }
});

Solution 2:

It think your problem is that you are creating the select after the DOM has been fully loaded and jQuery has already registered all events.

If you want to add dinamically N selects you should include a call to register it inside the code you are adding to the DOM, check this sample:

  <div id="select-container"></div>

  <script>
    function CreateSelect(id){
        return `<select id="ddl` + id +  `">
                    <option value="Opcion">Opcion<\/option>
                    <option value="Opcion2">Opcion 2<\/option>
                <\/select>
                <script>
                    RegisterSelectChangeEvent(` + id + `);
                <\/script>`;
    }

    function RegisterSelectChangeEvent(id){
      console.log("Event Raised");
      $("#ddl" + id).on("change", function (e) {
          jQuery("#select-container").append(CreateSelect(id+1));
      });
    }

    (function(){
         jQuery("#select-container").append(CreateSelect(1));
    })();
  </script>

You can see it working here:

https://codepen.io/anon/pen/LQRqYY

Post a Comment for "How To Create Multilevel Dynamic Dropdown Using Jquery"