Home > Mobile >  Selecting random radio button using JavaScript
Selecting random radio button using JavaScript

Time:01-26

Objective

I'm using Alchemer (formerly SurveyGizmo) to create a survey. To properly route my participants I need to create a hidden question with radio buttons (single choice) in combination with a JavaScript action that selects one of the radio buttons randomly. The JavaScript should execute automatically when the page was loaded.

What I did

I searched stackoverflow and the internet, found a couple JSFiddles that did similar things, tried reverse engineering a solution for me, but it wont work.

I have zero education regarding programming languages, just going with the little that I think I understand from looking at other peoples work.

Using "Inspect Element", I see that my radio buttons all have the class 'sg-input sg-input-radio", so I try collecting them using getElementsByClassName, not even sure if this is the way to approach this.

Here is what I got so far

$(document).ready(function(){
    var array = document.getElementsByClassName('sg-input sg-input-radio');
    var winnerButton;
    var numberOfButtons = array.length;

  
  function SelectRadio() {
    
    var randomNumber = Math.floor(Math.random() * numberOfButtons);
    
    winnerButton = array[randomNumber];
    
    winnerButton.checked = true;
   
    }
  
SelectRadio();
  
}

When the page loads, no radio button is selected.

I somehow feel like I'm close to having it work, but I need someone who knows what they're doing.

Cheers and thank you for taking the time!

CodePudding user response:

I think the getElementsByClassName may have problems with multiple classes. So I used querySelectorAll and it works.

Maybe it was a c p error, but in your example code a ); was missing.

$(document).ready(function(){
    var array = document.querySelectorAll('.sg-input.sg-input-radio');
    var winnerButton;
    var numberOfButtons = array.length;

  
  function SelectRadio() {
    var randomNumber = Math.floor(Math.random() * numberOfButtons);
    
    winnerButton = array[randomNumber];
    
    winnerButton.checked = true;
   
    }
  
    SelectRadio();
   
});

CodePudding user response:

The code you showed should work, but it require jQuery, and I don't know if it is available on the survey page. This is a solution without any dependency:

function selectRandomRadioButton(radioButtons) {
  const index = Math.floor(Math.random() * radioButtons.length);
  const element = radioButtons[index];

  element.checked = true;

  return `Selected Option ${element.value}`;
}

document.addEventListener('DOMContentLoaded', () => {
  const radioButtons = document.getElementsByClassName('sg-input sg-input-radio');

  const message = selectRandomRadioButton(radioButtons);
  console.log(message);
});
Option A:
<input type="radio"  value="A" name="x" /> Option B:
<input type="radio"  value="B" name="x" />

  •  Tags:  
  • Related