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?

Okami
  • 35
  • 6
  • 9
    Awesome, good luck, but where's the question? – DibsyJr Apr 21 '17 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. – Jeff Huijsmans Apr 21 '17 at 13:37
  • Possible duplicate of [How do you dynamically create a radio button in Javascript that works in all browsers?](http://stackoverflow.com/questions/118693/how-do-you-dynamically-create-a-radio-button-in-javascript-that-works-in-all-bro) – Teocci Apr 21 '17 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 –  Apr 21 '17 at 13:54

3 Answers3

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);
}
BabarConnect
  • 157
  • 6
  • Is there a way to have breaks in it so it's in a vertical list rather than horizontal? – Okami Apr 21 '17 at 15:51
  • Sure, you need to add `wrapper.appendChild(document.createElement('br'));` after `wrapper.appendChild(radio);` – BabarConnect Apr 21 '17 at 15:53
  • 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 – Okami Apr 22 '17 at 16:37
  • 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. – BabarConnect Apr 23 '17 at 13:11
  • 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 – Okami Apr 24 '17 at 14:37
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'));
}
Ethan
  • 4,165
  • 4
  • 22
  • 41
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>
Teocci
  • 4,348
  • 1
  • 34
  • 36