Is there a way to individually remove a selected radio button and its corresponding label?

Having trouble removing a selected radio button and its associated label. Struggling to implement the remove function that targets the selected radio button and removes both the button and label.

function removeRadioItem() {
  var radios = document.getElementsByName("attr_radio");
  for (var i = 0; i < radios.length; i++) {
    radio = radios[i];
    if (radio.checked) {
      radio.parentNode.removeChild(radio);
    }
  }
}

Check out the JsFiddle link for reference.

Answer №1

When using the addNewRadioItem function to add a new radio box, make sure to enclose it with either a span or div element (combining the radio button and label into one).

Similarly, in the removeRadioButton function, remove the enclosing element that contains the radio button and label.

function addNewRadioItem() {
  var htmlRadio = document.getElementById('radiopreview');
  var optionValue = document.getElementById('txtRadioValue');
  var optionDisplaytext = document.getElementById('txtRadioDisplayValue');

  if (optionValue.value == '') {
    alert('please enter option value');
    optionValue.focus();
    return false;
  }
  if (optionDisplaytext.value == '') {
    alert('please enter option display text');
    optionDisplaytext.focus();
    return false;
  }

  var radiobox = document.createElement("input");
  radiobox.type = 'radio';
  radiobox.value = optionDisplaytext.value;
  radiobox.id = optionValue.value;
  radiobox.name = 'attr_radio';

  var label = document.createElement('label')
  label.htmlFor = optionDisplaytext.value;

  var description = document.createTextNode(optionDisplaytext.value);
  label.appendChild(description);

  var radioDiv = document.createElement('span');
  radioDiv.appendChild(radiobox);
  radioDiv.appendChild(label);

  var container = document.getElementById('radiopreview');
  container.appendChild(radioDiv);

  alert("Option has been added successfully");
  optionValue.value = "";
  optionDisplaytext.value = "";

}

function removeRadioItem() {
  var radios = document.getElementsByName("attr_radio");
  for (var i = 0; i < radios.length; i++) {
    radio = radios[i];
    if (radio.checked) {
        var parentRadio = radio.parentNode;
      parentRadio.parentNode.removeChild(parentRadio);
    }
  }
}
<table border="0" align="float-left" id="radioForm">
  <tr>
    <td align="right">Preview</td>
    <td align="left">
      <div id="radiopreview"></div>
    </td>
  </tr>
  <tr>
    <td align="right">Option Value</td>
    <td align="left"><input name="txtRadioValue" type="text" id="txtRadioValue" value="" /></td>
  </tr>
  <tr>
    <td align="right">Option Display Text</td>
    <td align="left"><input name="txtRadioDisplayValue" type="text" id="txtRadioDisplayValue" /></td>
  </tr>
  <tr>
    <td align="right">&nbsp;</td>
    <td align="left"><input name="btnAddItem" type="button" id="btnAddRadioItem" value="Add Option"" onClick="addNewRadioItem();" /></td>
  </tr>
  <tr>
    <td align="right">&nbsp;</td>
    <td align="left"><input name="btnRemoveItem" type="button" id="btnRemoveRadioItem" value="Remove Option" onClick="removeRadioItem();" /></td>
  </tr>
</table>

Answer №2

The answer provided above is correct, but I have also implemented my own solution:

function createNewRadioButton() {
  var radioContainer = document.getElementById("radiopreview");
  var optionValue = document.getElementById("txtRadioValue");
  var optionDisplayText = document.getElementById("txtRadioDisplayValue");

  if (optionValue.value === "") {
    alert("Please enter an option value");
    optionValue.focus();
    return false;
  }
  if (optionDisplayText.value === "") {
    alert("Please enter an option display text");
    optionDisplayText.focus();
    return false;
  }

  var newRadio = document.createElement("input");
  newRadio.type = "radio";
  newRadio.value = optionDisplayText.value;
  newRadio.id = optionValue.value;
  newRadio.name = "attr_radio";

  var label = document.createElement("label");
  label.htmlFor = optionDisplayText.value;

  var description = document.createTextNode(optionDisplayText.value);
  label.appendChild(description);

  radioContainer.appendChild(newRadio);
  radioContainer.appendChild(label);

  alert("Option has been added successfully");
  optionValue.value = "";
  optionDisplayText.value = "";
}

function removeRadioButton() {
  var radioButtonList = document.getElementsByName("attr_radio");
  for (var i = 0; i < radioButtonList.length; i++) {
    let radioButton = radioButtonList[i];
    if (radioButton.checked) {
      let value = radioButton.value;
      radioButton.parentNode.removeChild(radioButton);
      let label = document.querySelector(`[for=${value}]`);
      label.parentNode.removeChild(label);
    }
  }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Custom Radio Buttons</title>
  </head>
  <body>
    <table border="0" align="float-left" id="radioForm">
      <tr>
        <td align="right">Preview</td>
        <td align="left">
          <div id="radiopreview"></div>
        </td>
      </tr>
      <tr>
        <td align="right">Option Value</td>
        <td align="left">
          <input name="txtRadioValue" type="text" id="txtRadioValue" value="" />
        </td>
      </tr>
      <tr>
        <td align="right">Option Display Text</td>
        <td align="left">
          <input
            name="txtRadioDisplayValue"
            type="text"
            id="txtRadioDisplayValue"
          />
        </td>
      </tr>
      <tr>
        <td align="right">&nbsp;</td>
        <td align="left">
          <input
            name="btnAddItem"
            type="button"
            id="btnAddRadioItem"
            value="Add Option"
            onClick="createNewRadioButton();"
          />
        </td>
      </tr>
      <tr>
        <td align="right">&nbsp;</td>
        <td align="left">
          <input
            name="btnRemoveItem"
            type="button"
            id="btnRemoveRadioItem"
            value="Remove Option"
            onClick="removeRadioButton();"
          />
        </td>
      </tr>
    </table>
    <script src="custom-script.js"></script>
  </body>
</html>

Answer №3

To remove the radio button along with its label, you can first remove the label that is the next sibling of the radio button and then remove the radio button itself

if (radio.checked) {
  radio.nextSibling.remove()
  radio.remove()
}

Check out this runnable example:

function addNewRadioItem() {
  var htmlRadio = document.getElementById('radiopreview');
  var optionValue = document.getElementById('txtRadioValue');
and so on...
...onClick="removeRadioItem();" /></td>
  </tr>
</table>

Answer №4

It's not ideal to directly manipulate the DOM like this, especially if you plan on transitioning to a framework like React in the future. It's best to avoid direct DOM manipulation.

My suggestion would be to keep track of all added radios in an array:

let radioArray = [];

Whenever a new radio is added, simply push it to the array:

let newRadio; // Define JSX or element with label for newRadio
radioArray.push(newRadio);

This way, you can easily access all radios in radioArray using methods like map or for-loop.

If you need to remove all radios, just clear the array:

radioArray = [];

You can also use Array.indexOf() to specifically remove a certain radio from the array.

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

What is the process for setting up redux in _app.tsx?

Each time I compile my application, I encounter the following error message: /!\ You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). Although my application functions correctly, I am unsure ...

What is causing the chat-widget to display a null value for the style read property?

Could someone assist me with hiding the Widget-chat? I keep getting an error that the property of style is null. Any help would be greatly appreciated. Thank you in advance. document.getElementById("chat-widget").style.display='none'; ...

utilizing a modal to trigger a function within the parent scope of an Angular application

I have a main.controller.js where there is a modal in place to notify the user of a warning before proceeding to the rest of the application. For example, I want to trigger my fileNew function from the modal. In main.controller.js: $scope.warningMod ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

Storing a collection of objects in session storage

I've been struggling to save an array containing the items in my online shopping cart. Even though both the object and the array are being filled correctly, when I check the sessionStorage, it shows an array with an empty object. I've spent a lot ...

Encountering a problem when trying to send an API request for multer in order to save

I encountered an issue with my node API that uses multer to store files. I am receiving an error when calling it and seeking assistance. Below is the code snippet along with the specific error message - Code - const storage = multer.diskStorage({ d ...

Showcasing information from a database on an HTML page with the use of Node

I am currently attempting to fetch data from my database and display it on an HTML page in a table using EJS for rendering. I found inspiration for my code on this website: Although the database connection is successful, I am encountering difficulties wit ...

Create a 3D representation of an inverted sphere using three.js

Currently, I am utilizing a plugin that integrates 360 / VR video functionality into our video player. The process involves the use of Three.js to generate a sphere and then applying the video as the material for this newly created sphere. By setting the v ...

Enhancing Transparency of WMS Layers in OpenLayers

I need help figuring out how to add transparency to a WMS layer in openlayers. Here is the current javascript code for a non-transparent layer: var lyr_GDPSETAAirtemperatureC = new ol.layer.Tile({ source: new ol.source.TileWMS(({ ...

The issue with CKEDITOR is that it fails to send data through ajax upon the initial submission

When using CKEDITOR, I am experiencing an issue where my forms do not send data to the server on the first submit. If I click the submit button once, empty fields are sent without any input from me. However, when I submit the form a second time, only then ...

Warning: Axios is sending duplicate CSRF-Tokens, resulting in a CSRF-Token mismatch

I am facing an issue with my Laravel/Vue with Sanctum setup. The problem is simple: When I send a token request and log in the user, the server responds with a new token. However, Axios is adding this new token along with an additional token that is alway ...

Issue with displaying the Bootstrap Autocomplete Input Dropdown

I've been struggling with this issue for hours now. Using Bootstrap 3, I am attempting to implement the bootstrap autocomplete input with ajax. The data is being retrieved successfully through Ajax, and I can confirm that. However, the dropdown menu i ...

Guidance on executing a JavaScript function from PHP or HTML

Although this may appear simple to some, I am relatively new to this and have been searching everywhere. I currently have a javascript function. mkfile : function(fm) { I am attempting to run this from an on-click event. Any suggestions? I apologize fo ...

Changing the text of a button using ngClass in Angular's toggle functionality

Is there a way to modify the text of a toggled button class in Angular using Bootstrap? Currently, I have this code to toggle the class: html <!-- toggle button --> <button type="button" class="btn btn-primary mt-3 ml-3" (click)="status=!status ...

Configuring Jest unit testing with Quasar-Framework version 0.15

Previously, my Jest tests were functioning properly with Quasar version 0.14. Currently, some simple tests and all snapshot-tests are passing but I am encountering issues with certain tests, resulting in the following errors: console.error node_modules/vu ...

React is encountering a problem with loading the image source and it is

<img src="play.jpg" alt="play"></img> This code works fine in standard HTML, but I'm having trouble getting it to work in React. Is adding it as a background the only solution? ...

What is the best way to interrupt the current song playing?

I am currently working on developing an audio player using reactjs that has a design similar to this https://i.sstatic.net/Hnw0C.png. The song boxes are rendered within a map function, and when any song box is clicked, it should start playing. However, I a ...

responding with a value of undefined for the get request

My current project involves URL shortening, but I keep encountering an 'undefined' result in my GET request. Additionally, sometimes I also receive a blank page as a result. Despite everything appearing to be correct based on my knowledge, I&apos ...

Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript. My approach involves running some Javascript code initially to obtain a ...

What could be causing this error I'm receiving: instance versus prototype difference?

Can someone help me understand the difference between .prototype and regular instances in JavaScript? I am confused about why this code is not working and getting a type error: "undefined is not a function". I am experimenting with the Ninja() class and ...