Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 20, 2023 › #dynamically #HowTo

How to dynamically create radio buttons from an array in JavaScript

In this article, we will write a program that create radio buttons from an array using JavaScript.

For that, we have the following array

let colors = ['Red','Green','Blue']

The following example dynamically creates radio buttons from the above array.

<div class="container"></div>
<script>
let colors = ['Red','Green','Blue']
colors.forEach((e)=>{
  let html = `<label><input type="radio" value="${e}" name="color"> ${e}</label>`;
  document.querySelector('.container').innerHTML += html;
})
</script>
  1. Fast we have a <div> element with a class container.
  2. We have also an array with three items named colors
  3. Using the forEach() method, we call an arrow function and pass a parameter e that represents all the item of the array.
  4. Inside the forEach() method, we create a variable named html and set its value to a <label>,<input> elements those values are set dynamically.
  5. Finally, selecting the <div> element, we append the variable html inside the <div> element as a child.
save
listen
AI Answer
Write Your Answer
loading
back
View All