Search code examples
javascripthtmldropdown

Delete dropdown list from list of dropdown lists in javascript


I have this code from geeksforgeeks that I modified. The original code would add and delete from a list of textareas. I tried to do the same with dropdown lists. But, it does not work as expected. The changes I would like to make are:

  1. On pressing the "Add item" button, the drop down list should be added below the previous one.
  2. On clicking the "Remove item" button, the bottom most drop down list should be removed.

Here is the link to my current code: https://jsfiddle.net/coderr/dq12vL4j/

HTML

<ul id="list"></ul>
 
    <input type="text" id="candidate" />
    <button onclick="addItem()" class="buttonClass">
    Add item</button>
    <button onclick="removeItem()" class="buttonClass">
    Remove item</button>

Javascript

var myParent = document.body;

//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];

//Create and append select list
function addItem() {
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);

//Create and append the options
for (var i = 0; i < array.length; i++) {
    var option = document.createElement("option");
    option.value = array[i];
    option.text = array[i];
    selectList.appendChild(option);
}
}
        // Creating a function to remove item from list
        function removeItem() {

            // Declaring a variable to get select element
            var a = document.getElementById("list");
            var candidate = document.getElementById("candidate");
            var item = document.getElementById(candidate.value);
            a.removeChild(item);
        }

Thanks!


Solution

  • Changed the removeItem() function so now it removes the last child of the div which contains all the drop down lists. Also added a display: block; to the div to

    const list = document.getElementById('list')
    var myParent = document.body
    
    //Create array of options to be added
    var array = ['Volvo', 'Saab', 'Mercades', 'Audi']
    
    //Create and append select list
    function addItem() {
      var selectList = document.createElement('select')
      selectList.id = 'mySelect'
      selectList.style.display = 'block'
      myParent.appendChild(selectList)
    
      //Create and append the options
      for (var i = 0; i < array.length; i++) {
        var option = document.createElement('option')
        option.value = array[i]
        option.text = array[i]
        selectList.appendChild(option)
      }
      list.appendChild(selectList)
    }
    
    // Creating a function to remove item from list
    function removeItem() {
      list.lastChild?.remove()
    }
    <input type="text" id="candidate" />
    <button onclick="addItem()" class="buttonClass">Add item</button>
    <button onclick="removeItem()" class="buttonClass">Remove item</button>
    <div id="list"></div>