Search code examples
javascripthtmlradio-buttonsurvey

Selecting random radio button using JavaScript


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!


Solution

  • 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" class="sg-input sg-input-radio" value="A" name="x" /> Option B:
    <input type="radio" class="sg-input sg-input-radio" value="B" name="x" />