Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically.

Unfortunately, I have run into an issue where the delete function does not work when the button is pressed.

Here is the code I am using:

var selectionCounter = 0;

function cloneSelect() {
  var select = document.getElementById("List");
  var clone = select.cloneNode(true);
  var name = select.getAttribute("name") + selectionCounter++;
  clone.id = name;
  clone.setAttribute("name", name);
  document.getElementById("selectContainer").appendChild(clone)
}
function deleteSelect() {                                                          
var select = document.getElementById("roomList");                              
var existingNode = select.cloneNode(true);                                     
var name = select.getAttribute("name") + selectionCounter--;                   
document.getElementById("selectContainer").parentNode.removeChild(existingNode)
}                                                                                  

  
<div id="selectContainer">
  <select id="List" name="List" required>
    <option>Populated by php<option>        
  </select>
</div>
<button onclick="cloneSelect()"  type="submit" class="button">Add Room</button>
<button onclick="deleteSelect()"  type="submit" class="button" >Delete Room</button>

Answer β„–1

  1. Change the type of buttons to actual buttons instead of submit
  2. Avoid deleting a clone element.

var counter = 0;

function duplicateSelection() {
  var selectElement = document.getElementById("List");
  var clonedSelect = selectElement.cloneNode(true);
  var nameAttribute = selectElement.getAttribute("name") + counter++;
  clonedSelect.id = nameAttribute;
  clonedSelect.setAttribute("name", nameAttribute);
  document.getElementById("selectContainer").appendChild(clonedSelect)
}

function removeSelection() {
  counter--;
  var selected = document.getElementById("List"+(counter));
  if (selected) document.getElementById("selectContainer").removeChild(selected);
}
<div id="selectContainer">
  <select id="List" name="List" required>
    <option>Content inserted by PHP<option>        
  </select>
</div>
<button onclick="duplicateSelection()" type="button" class="button">Add Selection</button>
<button onclick="removeSelection()" type="button" class="button">Remove Selection</button>

Answer β„–2

When it comes to the deleteSelect() method, you are currently cloning the node instead of targeting the existing one for removal.

//Create a valid id
var name = select.getAttribute("name") + --selectionCounter;
//Target the element
var clone = document.getElementById(name);
//Remove the element
clone.parentNode.removeChild(clone);

Furthermore, remember to set your buttons' type attribute to "button".

var selectionCounter = 0;

function cloneSelect() {
  var select = document.getElementById("List");
  var clone = select.cloneNode(true);
  var name = select.getAttribute("name") + selectionCounter++;
  clone.id = name;
  console.log(name)
  clone.setAttribute("name", name);
  document.getElementById("selectContainer").appendChild(clone)
}

function deleteSelect() {
  var select = document.getElementById("List");
  //Create a valid id
  var name = select.getAttribute("name") + --selectionCounter;
  //Target the element
  var clone = document.getElementById(name)
  clone.parentNode.removeChild(clone)
}
<div id="selectContainer">
  <select id="List" name="List" required>
    <option>Populated by php<option>        
  </select>
</div>
<button onclick="cloneSelect()"  type="button" class="button">Add Room</button>
<button onclick="deleteSelect()"  type="button" class="button" >Delete Room</button>

Answer β„–3

To access the most recently added <select> element, you can use container.lastElementChild. Here, container represents the <div id="selectContainer"> element:

var counter = 0
var container = document.getElementById("selectContainer")
var select = document.getElementById("List")

function cloneSelect() {
  var clone = select.cloneNode(true)
  clone.id = clone.name = (select.name + counter++)
  container.appendChild(clone)
}

function deleteSelect() {
  if (counter) {
    counter--
    container.removeChild(container.lastElementChild)
  }
}
<div id="selectContainer">
  <select id="List" name="List" required>
    <option>Populated by php<option>        
  </select>
</div>
<button onclick="cloneSelect()" type="submit" class="button">Add Room</button>
<button onclick="deleteSelect()" type="submit" class="button">Delete Room</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, ...

It is impossible to add a promise's value to an array

When attempting to push values into an array and return them, the console only displays an empty array or shows undefined! The issue seems to be that .then does not properly pass the value to the array. const net = require('net'); const find = re ...

I feel overwhelmed and confused by Node, Express, domains, and uncaught exceptions

After hours of research on exception handling in Node, I've come to understand the drawbacks of using uncaughtException. It's clear that shutting down the process can prevent any potential "unknown state" scenarios where anything may happen. The ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Executing a JavaScript function to submit an HTML form and circumvent the default behavior

Currently, I am utilizing a virtual keyboard that was created using JavaScript for the user interface on an embedded system. If you would like to access the source code for this virtual keyboard, you can find it here: https://codepen.io/dcode-software/pen ...

Placing error notifications beneath my table rows for a more polished appearance

In the process of creating a review page for my app that showcases uploaded files, I've encountered an issue. Whenever a user uploads files with errors, I want to display a warning message below each specific file. Currently, I'm able to show the ...

Guide on launching Selenium within an already open browser using manual settings

Issue The default behavior of Selenium is to open a new browser window during execution. However, I am looking to have Selenium operate within an existing browser session (preferably in Google Chrome). While there are solutions available in Java and Pytho ...

Sending data with the request body using Express and Passport

I've created a login application using Express and Passport, but I'm having trouble directing the user to their specific user profile page. The goal is for users to fill out an HTML form and then be redirected to their own profile page (which dif ...

The z-index is preventing me from selecting a certain area

I'm currently facing a challenge with a Bootsrap card that seems to be unclickable and I am unable to type input into the form inside of it. The root cause appears to be related to the z-index that I used to position the card "behind" the header and f ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Aggregating MongoDB: Calculating unique values within an array

Looking to find the distinct tags count on all records within a mongodb query, utilizing JS. Data structure of the record: { "_id": { "$oid": "62e593aed8fd9808777225e8" }, "title": "β€œThe world as ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

Error message: Unexpected character found at the beginning of JSON data - REST API using node.js and Express

Recently, I have embarked on the journey of learning REST API with node and express. My main goal is to achieve file read and write operations using APIs. However, a frustrating error arises when attempting to hit the API through Postman. Strangely enough, ...

What is the best way to grab the initial section of a website's text while using a WKWebView?

When working with a WKWebView, retrieving the webpage's title is simple using webView.title. However, obtaining the first paragraph of the webpage's content poses a challenge with no straightforward solution. Any tips or suggestions on how to ac ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Learning how to utilize various types of buttons in C# and ASP.NET with this

I was following this tutorial: I like everything the same except I want to make the following change: <section> <a rel="external" href="#button" id="button">&#xF011;</a> <span></span> </section> ...

The counter unexpectedly increments by 2 instead of 1

I'm attempting to create a counter that increases by one each time according to the code snippet below: var imnum = 0; (function changeImage() { ++imnum; $( ".slider" ).fadeOut(5000, function() { $('#home-slider-im').attr("s ...