1

I want to be able to have an array(such as the one below):

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

that will take those values (no matter how many are in the array) and populate radio buttons. I also want to be able to have the radio buttons randomly populated from the array list. such as:

var random = myArray[Math.floor(Math.random() * myArray.length)];

I also want to try and do this only in JavaScript and HTML if possible since I am still new to programming.

How do you make radio buttons be populated by an array in JavaScript? And how can you randomly pick options from the array to be populated into the radio buttons randomly?

4
  • 9
    Awesome, good luck, but where's the question? Commented Apr 21, 2017 at 13:34
  • To elaborate: if you have a specific question, SO is the way to go. If you want general help/tutorials, please search Google. This is not a tutorial website. Commented Apr 21, 2017 at 13:37
  • Possible duplicate of How do you dynamically create a radio button in Javascript that works in all browsers? Commented Apr 21, 2017 at 13:52
  • I'd suggest that you make use of array.splice() using array length as your upper bound for random and terminating the loop when length is 0 Commented Apr 21, 2017 at 13:54

3 Answers 3

2

First, set up the HTML :

<div id="wrapper"></div>

Then the JavaScript :

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

var wrapper = document.getElementById('wrapper');

var elementsToInsert = [];

// Creation of the input with radio type and the labels
for(var i = 0; i < myArray.length; i++) {
  var radio = document.createElement('input');
  var label = document.createElement('label');
  radio.type = 'radio';
  radio.name = myArray[i];
  radio.value = myArray[i];

  label.setAttribute("for", myArray[i]);
  label.innerHTML = myArray[i];

  elementsToInsert.push({ label: label, radio: radio });
}

// Insert the labels and input in a random order
while(elementsToInsert.length !== 0) {
  var randomIndex = Math.floor(Math.random() * elementsToInsert.length);

  // Array.prototype.splice removes items from the Array and return the an array containing the removed items (See https://www.w3schools.com/jsref/jsref_splice.asp)
  var toInsert = elementsToInsert.splice(randomIndex, 1)[0];

  wrapper.appendChild(toInsert.label);
  wrapper.appendChild(toInsert.radio);
}

The idea is to create the inputs and the labels, and populate an array with them.

Then, you select a random item (label and radio input) from this array, add the label and the input into the wrapper element, and remove this item from the array

Edit

You could also do all this in a single while :

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

var wrapper = document.getElementById('wrapper');

var elementsToInsert = [];

while(myArray.length) {
  var randomIndex = Math.floor(Math.random() * myArray.length);

  var value = myArray.splice(randomIndex, 1)[0];
  var radio = document.createElement('input');
  var label = document.createElement('label');

  radio.type = 'radio';
  radio.name = value;
  radio.value = value;

  label.setAttribute("for", value);
  label.innerHTML = value;

  wrapper.appendChild(label);
  wrapper.appendChild(radio);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to have breaks in it so it's in a vertical list rather than horizontal?
Sure, you need to add wrapper.appendChild(document.createElement('br')); after wrapper.appendChild(radio);
thanks! is there also a way to have only one radio button checked at a time? i know how to do it when you have radio buttons listed in html but not sure how you can do it when it's not in html
Sure, only one radio will be checked at a time if they have the same name. This means that you need to change radio.name = value; to radio.name = 'country'; or any other name.
so in the code you posted above, if i'ts radio.name = myArray[i], is there a way to get that to have only one radio button checked off at a time? or would it be better to use the single while loop? Trying to make sure I understand the code well enough since I'm still new to programming
0

Probably this is what you need:

var nacionalities = ['Asian', 'Thai', 'Korean', 'Chinese', 'Mexican'];
var random;
var elements = [];
var content = document.getElementById('content');
var generateBtn = document.getElementById('generate');
generateBtn.addEventListener('click', generateRadioElements)

function generateRadioElements() {
  content.innerHTML = '';
  nacionalities.forEach(function(nacionality) {
    elements.push(createRadioElement(nacionality));
  });

  // Append the labels and input in a random order to the content
  while (elements.length !== 0) {
    random = Math.floor(Math.random() * elements.length);
    var element = elements.splice(random, 1)[0];

    content.appendChild(element.label);
    content.appendChild(element.input);
    if (elements.length > 0) content.appendChild(createSeparator());
  }
}

function createRadioElement(value) {
  var radioLabel = document.createElement('label');
  radioLabel.innerHTML = value;
  var radioInput = document.createElement('input');
  radioInput.setAttribute('type', 'radio');
  radioInput.setAttribute('name', 'nacionalities');
  radioInput.setAttribute('value', value);
  return {
    label: radioLabel,
    input: radioInput
  };
}

function createSeparator() {
  var spanSeparator = document.createElement('span');
  spanSeparator.style.padding = "0px 10px 0px 10px";
  return spanSeparator;
}
<div id="generate">Click to generate</div>
<div id="content"></div>

Comments

0

This code will create a radio button for each element of the array, but in a random order.

It works by first shuffling the array, and then iterating through it and creating a radio element, the label text and a br tag for each element in the array.

var myArray = ["Asian", "Thai", "Korean", "Chinese", "Mexican"];

/**
 * Randomize array element order in-place.
 * Using Durstenfeld shuffle algorithm.
 */
function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

// Shuffle the array.
myArray = shuffleArray(myArray);

// Iterate and create an input, label and line break.
for (var i = 0; i < myArray.length; i++) {
  // Create the radio element.
  var radioElement = document.createElement('input');
  radioElement.type = "radio";
  radioElement.name = "nationality";
  radioElement.value = myArray[i].toLowerCase();
  document.body.appendChild(radioElement);

  // Create the label.
  var radioLabel = document.createTextNode(myArray[i]);
  document.body.appendChild(radioLabel);

  document.body.appendChild(document.createElement('br'));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.