Skip to content Skip to sidebar Skip to footer

Create New Drop Downs On Change Event Using JQuery

I have drop down menu with some random values. When I select the value onchange event triggers and I want to add new drop down under it, but the new one should have all values exce

Solution 1:

We can do it in following way:

We are just adding some class like executed once it add another dropdown. And in event handler we are checking if current dropdwon has that class or not. If it is already there then it means we are already done with that dropdown as follows:

$(document).ready(function() {
  var selectWrapper = $('#select-boxes');
  $(document).on('change', '.dynamic-select', function() {
    var element = $(this);
    if(element.hasClass("executed"))
      return;
    
    var optionsLength = (element.find('option').length) - 1;

    if (optionsLength === 1) {
      return true;
    }

    var newSelect = $(this).clone();
    newSelect.find("option[value='" + element.val() + "']").remove();
    newSelect.appendTo(selectWrapper)
    
    $(this).addClass("executed");
    
  });
});
.dynamic-select {
  display: block;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="select-boxes">
  <select class="dynamic-select" id="ddlTest">
    <option value=""></option>
    <option value="Belbin">Belbin</option>
    <option value="Raven">Raven</option>
    <option value="PPA">PPA</option>
    <option value="PPA+">PPA+</option>
    <option value="Basic Knowledge">Basic Knowledge</option>
    <option value="PCT">PCT</option>
  </select>
</div>

Post a Comment for "Create New Drop Downs On Change Event Using JQuery"