How create radio button with js?

Have a look at this. But be warned it is a bit beyond a beginner…

The example shows how to create the forms by reading the information from arrays of information.
I have put the info in the code of the example but it can easily be read from an external file.

This is the js code used

 //-- your would have your questions in an exernal .js file  that you would access by including a link to it.
 //-- But to simplfy this example I have the questions inline here showing how to structure the external file.

var questions =  [ 	
{questionId:"question1", formName:"form1",radioName:"gender",values:[  "Male", "Female" , "Other"]},
{questionId:"question2", formName:"form2",radioName:"abode",values:[  "House", "Flat" , "Studio"]}

      ];



//-- we iterate over each question

for (i = 0; i < questions.length; i++) { 
   var question;
   var theInput;
   
   var thisQuestion = questions[i];
   
   //-- we get the values arrary for the question
   var theValues =   thisQuestion.values;
   
   //-- we creat a label element for the text label.
   var label = document.createElement( 'label');
   
   //-- we create the form element 
   var theForm = document.createElement("form");
   //-- we set the forms name
   theForm.setAttribute('name',thisQuestion.formName);
 
  //-- we iterate over each value and create a input for it and we add the value
  for (q = 0; q < theValues.length; q++) { 
  
  theInput = document.createElement("input");

  theInput.setAttribute('type',"radio");
  
  theInput.setAttribute('name',thisQuestion.radioName);
  theInput.setAttribute('value',theValues[q]);
 
  
  //-- we add the input to its text label.  ( put it insdie of it )
  label.appendChild(theInput);
  label.innerHTML += "<span> " + theValues[q] + "</span><br>";
  //--we add the label to the form.
  theForm.appendChild( label);
  }
 
   //-- we get the correct Hype element to append to.
 question = hypeDocument.getElementById(thisQuestion.questionId);
 question.appendChild(theForm);
  

}

.RadioBtns_MH_v1.hype.zip (19.5 KB)

1 Like