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

Receive information from a form and store it in an array

Struggling to figure out how to convert this into an array. I'm having trouble grasping the concept of taking input from a form and storing it in an array. In my project instructions, it clearly states: Do NOT save the input in variables and then tra ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

Displaying information collected from a submission form

I am in the process of designing a cheerful birthday card and I need to transfer data from a form to the birthday card page. How can I take information from the first div (which contains the form) and display that data in the second div? <!DOCTYPE ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

Pass an array from JavaScript to PHP

I am attempting to send an array to the server using jQuery. Here is my code snippet for sending the array: jQuery(document).ready(function($){ $.ajax({ type: "POST", url: "file.php", datatype : "json", data : JSON.str ...

Clicking on "Ng-Click" will add a fresh row to the table using Angular

Is there a way to insert a new row into a table using ng-click? I currently have the following setup with the data stored in an array. Here is how my array looks. $scope.workflows = [{ Id: 1, Name: "Workflow Page 1", ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

What is the process for enabling HTMLField in Django Admin and ensuring it is accurately displayed on the template?

One of the models in my Django app is for dorms and it looks like this: class Dorm(models.Model): dorm_name = models.CharField(max_length=50, help_text="Enter dorm name") dorm_description = models.TextField(max_length=1000, help_text="Enter dorm d ...

socket.io establishes several sockets for each connection

At times, when the server is experiencing some load, connecting to the page may result in multiple sockets being created. If there is significant lag, the connection may never be established while additional sockets are generated every second indefinitely. ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

Using a Hook inside a React function is not possible

I encountered an error message known as the "invalid hook call error" while using the useEffect hook in my code. According to the documentation, this issue usually arises due to either a version mismatch or incorrect function calls. Could someone kindly r ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

Personalized parameters in communication for Quickblox's JavaScript

Sending a chat message with custom parameters to the Quickblox API involves specifying various details such as the body of the message, date sent, dialog ID, and more. For example: message: { body: 'something', date_sent: 'some date&apo ...

PHP and MySQL with jQuery and AJAX combine to create a real-time news feed update system similar to Twitter

Is there a way to automate the news feed on my website so that it periodically checks for new status updates? I would like it to display a button labeled "(?) New Messages" when there are new updates, and then load only the new ones when the button is clic ...

What is the best approach to link an HTML document to a MySQL Workbench server utilizing JavaScript, Ajax, and PHP?

On my HTML page, users can enter the name of a movie and if it is found in the database, the name will be displayed. I am attempting to establish a connection to the MySQL Workbench Server using JavaScript, Ajax, and PHP. This is what I have implemented s ...

What is the correct method for formatting text spacing?

A few months ago, I dabbled in web design and created a basic website. Now, I'm revisiting it to clean up the layout and make it more visually appealing. I initially used non-breaking spaces to separate paragraphs, but I know that's not optimal. ...

The jQuery form submission functionality fails to execute properly in the presence of a callback function

I have been on the hunt for a solution to this problem, but unfortunately I haven't been able to find one. The issue at hand is that when using the jQuery Submit function with a button and a callback function defined, it doesn't seem to work. Her ...

Center the p tag vertically

To ensure the text inside the p tag aligns vertically in the middle, I've set a specific height for the tag. While this works perfectly for single-line text, it shifts to the top of the p tag when there are two lines of text. It's important to k ...