How to dynamically create radio buttons using an array in JavaScript?

Creating radio buttons dynamically using an array in JavaScript is a useful way to provide users with multiple options for input. When the user clicks on one of the radio buttons, it will be selected and any other choices will be deselected automatically.

This process can be automated by looping through an array that contains all the possible values and creating a new radio button element for each item in the array.

To dynamically create radio buttons using an array, use the concept of createElement() and appendChild(). Let's look at the concept to understand more about dynamically creating radio buttons.

The createElement() Method

JavaScript's createElement() function can be used to dynamically create an HTML element node with the given name. The element node is created by this method using the element's name as an argument.

The appendChild() function or insertBefore() method can be used to insert a newly produced element in the page after it has been created.

Syntax

document.createElement(nodename);

The appendChild() Method

The Node interface's appendChild() method adds a node to the end of the list of children of a given parent node. AppendChild() moves the supplied child, if it is a reference to an existing node in the document, from its present position to the new position.

Syntax

appendChild(aChild)

Example 1: Static Radio Buttons

In the following example we are running the script to create a radio button.

<!DOCTYPE html>
<html>
<body>
   Choose Gender:
   <input type="radio" name="gender" value="Male">Male
   <input type="radio" name="gender" value="Female">Female
   <input type="radio" name="gender" value="Others">Others<br>
   <button type="button" onclick="radiobutton()">Submit</button><br>
   <div id="result"></div>
   <script>
      function radiobutton() {
         var ele = document.getElementsByName('gender');
         for(i = 0; i < ele.length; i++) {
            if(ele[i].checked)
            document.getElementById("result").innerHTML = "Gender: "+ele[i].value;
         }
      }
   </script>
</body>
</html>
When the script gets executed, it will generate an output consisting of radio buttons along with a submit. When the user selects the radio button and clicks the submit button, it will display the gender that was selected by the user.

Example 2: Creating Radio Buttons Dynamically from Array

In this example, we create radio buttons dynamically using an array of options. Each array item becomes a radio button with proper labeling.

<!DOCTYPE html>
<html>
<body>
   <div id="container"></div>
   <button onclick="createRadioButtons()">Create Radio Buttons</button>
   <button onclick="getSelectedValue()">Get Selected Value</button>
   <div id="result"></div>
   
   <script>
      function createRadioButtons() {
         var options = ['JavaScript', 'Python', 'Java', 'C++', 'PHP'];
         var container = document.getElementById('container');
         
         // Clear existing content
         container.innerHTML = '<h3>Choose your favorite programming language:</h3>';
         
         options.forEach(function(option, index) {
            // Create radio input
            var radioButton = document.createElement('input');
            radioButton.type = 'radio';
            radioButton.name = 'language';
            radioButton.value = option;
            radioButton.id = 'option' + index;
            
            // Create label
            var label = document.createElement('label');
            label.htmlFor = 'option' + index;
            label.appendChild(document.createTextNode(option));
            
            // Create line break
            var br = document.createElement('br');
            
            // Append to container
            container.appendChild(radioButton);
            container.appendChild(label);
            container.appendChild(br);
         });
      }
      
      function getSelectedValue() {
         var radios = document.getElementsByName('language');
         for(var i = 0; i < radios.length; i++) {
            if(radios[i].checked) {
               document.getElementById('result').innerHTML = 'Selected: ' + radios[i].value;
               return;
            }
         }
         document.getElementById('result').innerHTML = 'No option selected';
      }
   </script>
</body>
</html>
When executed, clicking "Create Radio Buttons" generates radio buttons from the array. The "Get Selected Value" button displays which option was chosen.

Example 3: Advanced Dynamic Radio Buttons with Data

This example shows creating radio buttons from an array of objects with more complex data structure.

<!DOCTYPE html>
<html>
<body>
   <div id="productContainer"></div>
   <button onclick="createProductOptions()">Load Products</button>
   <button onclick="showSelection()">Show Selection</button>
   <div id="output"></div>
   
   <script>
      function createProductOptions() {
         var products = [
            {id: 1, name: 'Laptop', price: 999},
            {id: 2, name: 'Phone', price: 599},
            {id: 3, name: 'Tablet', price: 399},
            {id: 4, name: 'Watch', price: 299}
         ];
         
         var container = document.getElementById('productContainer');
         container.innerHTML = '<h3>Select a product:</h3>';
         
         products.forEach(function(product) {
            var radioButton = document.createElement('input');
            radioButton.type = 'radio';
            radioButton.name = 'product';
            radioButton.value = JSON.stringify(product);
            radioButton.id = 'product' + product.id;
            
            var label = document.createElement('label');
            label.htmlFor = 'product' + product.id;
            label.appendChild(document.createTextNode(product.name + ' - $' + product.price));
            
            var div = document.createElement('div');
            div.appendChild(radioButton);
            div.appendChild(label);
            
            container.appendChild(div);
         });
      }
      
      function showSelection() {
         var radios = document.getElementsByName('product');
         for(var i = 0; i < radios.length; i++) {
            if(radios[i].checked) {
               var selectedProduct = JSON.parse(radios[i].value);
               document.getElementById('output').innerHTML = 
                  'Selected Product: ' + selectedProduct.name + 
                  '<br>Price: $' + selectedProduct.price;
               return;
            }
         }
         document.getElementById('output').innerHTML = 'No product selected';
      }
   </script>
</body>
</html>
This creates radio buttons for products with names and prices. When selected, it displays the complete product information.

Key Points

  • Use createElement('input') to create radio button elements
  • Set the type attribute to 'radio'
  • Give all radio buttons in a group the same name attribute
  • Use appendChild() to add elements to the DOM
  • Create labels for better user experience and accessibility
  • Use forEach() to iterate through arrays efficiently

Conclusion

Creating radio buttons dynamically from arrays allows for flexible, data-driven user interfaces. Use createElement() and appendChild() to generate radio buttons programmatically, ensuring proper naming and labeling for functionality and accessibility.

Updated on: 2026-03-15T23:19:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements