The radio button created with createElement() in a for loop does not allow for deselection

Can anyone help with creating radio buttons using createElement() in a loop? I have successfully created the radio buttons, but when selecting a second radio button after the first one is selected, the first one does not get deselected. Here is the link to the Plunker showcasing the customized radio buttons creation using createElement(). Any assistance would be greatly appreciated.

function myFunction() {
  var obdiv = document.getElementById("odiv")
  for (var i = 0; i < 5; i++) {
    var y = document.createElement("LABEL")
    var att = document.createAttribute("class")
    att.value = "container"
    y.setAttributeNode(att)
    var spane = document.createElement("span")
    var spanatt = document.createAttribute("class")
    spanatt.value = "checkmark"
    spane.setAttributeNode(spanatt)
    const btn = document.createElement('input')
    btn.type = 'radio'
    y.appendChild(btn)
    y.appendChild(spane)
    obdiv.appendChild(y)
  }
}
/* The container */
.container {
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default radio button */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */
.container:hover input~.checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */
.container input:checked~.checkmark {
  background-color: #2196F3;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */
.container input:checked~.checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */
.container .checkmark:after {
  top: 9px;
  left: 9px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
}
<body onload="myFunction()">
  <div id="odiv"></div>
</body>

Answer №1

If you want to group the radio buttons, simply add btn.name="yourname"

In order to organize the radio buttons into groups, you must specify a name for them.

function myFunction() {
  var obdiv = document.getElementById("odiv")
  for (var i = 0; i < 5; i++) {
    var y = document.createElement("LABEL")
    var att = document.createAttribute("class")
    att.value = "container"
    y.setAttributeNode(att)
    var spane = document.createElement("span")
    var spanatt = document.createAttribute("class")
    spanatt.value = "checkmark"
    
    spane.setAttributeNode(spanatt)
    const btn = document.createElement('input')
    btn.type = 'radio'
    btn.name="yourname"
    y.appendChild(btn)
    y.appendChild(spane)
    obdiv.appendChild(y)
  }
}
/* The container */
.container {
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default radio button */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */
.container:hover input~.checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */
.container input:checked~.checkmark {
  background-color: #2196F3;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */
.container input:checked~.checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */
.container .checkmark:after {
  top: 9px;
  left: 9px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
}
<body onload="myFunction()">
  <div id="odiv"></div>
</body>

Answer №2

I recommend assigning a name to the radio buttons (btn.name = 'radio_group');.

function myFunction(){
var obdiv = document.getElementById("odiv")
for(var i=0;i<5;i++){
var y = document.createElement("LABEL");
          var att = document.createAttribute("class") 
          att.value = "container";  
          y.setAttributeNode(att) ; 
          var spane = document.createElement("span");
          var spanatt = document.createAttribute("class");
          spanatt.value = "checkmark";
          spane.setAttributeNode(spanatt);
          const btn = document.createElement('input');
          btn.type = 'radio';
          btn.name = 'radio_group';
          y.appendChild(btn);
          y.appendChild(spane);
          obdiv.appendChild(y);
  }
}
/* The container */
.container {
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

/* Hide the browser's default radio button */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
background-color: #ccc;
}

/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
background-color: #2196F3;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}

/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
display: block;
}

/* Style the indicator (dot/circle) */
.container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="myFunction()">
</body>
<div id = "odiv"></div>

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

Setting up JavaScript within a .NET Framework MVC project: A Step-by-Step Guide

Seeking guidance on integrating JavaScript into an MVC project within the .NET framework. Have attempted various tutorials with no luck so far, any help is appreciated. Thank you. ...

What could be causing Node to encounter difficulties in locating the SubmitEvent?

I'm currently integrating unit tests with jest into my React app. The code snippet I have in my test is giving me trouble, as it throws a "ReferenceError: SubmitEvent is not defined" when executed. taskInputForm.dispatchEvent(new SubmitEvent("submit" ...

A guide on changing the background color to complement the light/dark theme in Bootstrap 5.3

In the latest version of Bootstrap, 5.3, users have the ability to select a theme for their websites. The built-in options include a Dark theme and a Light theme. For instance, by setting <html data-bs-theme="dark">, you can specify that t ...

Utilizing Bootstrap4 Grid System: Flex for SM and beyond, Row then Column for XS viewports

I'm in the process of developing a menu system specifically tailored for XL, LG, MD, SM screens in BOOTSTRAP4 while offering a unique appearance for XS (mobile) devices. Here is the HTML code I currently have: <div class="container-fluid"> ...

How to prevent multiple instances of setTimeout executing

I am facing a particular issue with my music application development using JavaScript and other technologies. I have analyzed the module architecture in Engine and UI, and the problem seems to be within the Engine Modules. Specifically, I have a main Engin ...

Adjusting Font Size in Angular Material Design

Recently, I incorporated https://material.angularjs.org/latest/ to optimize the responsive design of my website. One key feature I am focusing on is adjusting the font size based on different screen sizes. For smaller screens, I intend to set the font siz ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

Issues with Twitter-Bootstrap Modal Functionality

After creating a modal dialogue: <a href="#myModal" role="button" class="btn" data-toggle="modal" id="LaunchDemo">Click here to launch the demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="di ...

PHP output not displaying <div> tag properly

Why does the <?php echo $userPasswordError; ?> line return empty instead of <div class="invalid-feedback">Too long.</div> when a password containing more than 1 character is entered with the code below? When I replace this line: $userPas ...

Adding elements to a list using the appendChild method

Hey there! I have a bunch of images and I'm trying to create a navigation list item for each image. Here's the code I currently have: var bigImages = $('#imagesList li img'); // grabs the Big Images Next, I've set up a ul with t ...

The divs descend one after another with no problems related to margins or padding

Having some trouble creating a unique WordPress theme with Bootstrap3. I can't seem to get my divs to behave properly and I've tried everything from display: inline, vertical-align: top, floats, clears, etc... but nothing seems to work. Here is ...

Unable to locate the element within a component using Cypress

I need help locating the dropdown arrow. I tried using the Cypress command cy.get('.dropdown-arrow').click() but it's throwing an error saying element not found. Below is the code snippet: <widgets-bms-scoreboard> <div class=&q ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Are there any methods for integrating a database file directly into an HTML file? If not, are there alternative approaches I could explore to achieve a similar result?

I have a school project where I need to create a website showcasing my work. I've created a database in Microsoft Access and I'm wondering if there's a way to integrate it into my website using html. The database is simple, just a table, a f ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

Failed to parse server response using $.parseJSON

Here are two basic functions I have: function getBatchSliceInfo(batch_num){ //retrieves batch slice info for the specified batch_num alert('batch num is ' + batch_num); //correctly returns the batch_num $.getJSON("statistics_batchdb. ...

Issue with maintaining fixed positioning of css elements while scrolling

I'm currently working on a school project and I seem to be encountering an issue with the positioning of the slider I created. Specifically, I am having trouble getting the bottom fixed position for it. The problem arises when scrolling the page, as t ...

Next step is to retrieve previous store information

As a newcomer to the world of Javascript and Reactjs, I encountered an issue while attempting to execute multiple actions upon clicking a button. The first action successfully updates the store data, however, the second action seems to be using the old sto ...

Using THREE.js: Finding the nearest point between two rays in a THREE.js environment

In my current project with THREE.js, I am working with two THREE.Ray objects. Both rays have an origin point represented by a Vector3 and a direction indicated by another Vector3. I am currently exploring how to determine the nearest intersection point be ...

Accessing properties of objects using specific keys

In my coffeescript code, I am attempting to retrieve the keys from an object where the key matches a specific value. However, in addition to the object's own properties, I am also getting function properties in my result. This issue is causing an err ...