mardi 27 septembre 2016

how to create radio buttons by JS.

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on... my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:

enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  console.log(this.responseText);
  var data = JSON.parse(this.responseText);
  document.getElementById("my_test").innerHTML  = data.question;

  // Send the answer to next URL
  if(data.alternatives !== null){
    createRadioElement(div,);
  }
  var answerJSON = JSON.stringify({"answer":"2"});
  sendAnswer(data.nextURL, answerJSON)
   }
 };
 xhttp.open("GET", url, true);
 xhttp.send();
 }

function sendAnswer(url, data) {
  xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function () {
   if (xhr.readyState == 4 && xhr.status == 200) {
      var data = JSON.parse(this.responseText);
      console.log(this.responseText);

      loadDoc(data.nextURL);
    }
 }
  // var data =        JSON.stringify({"email":"hey@mail.com","password":"101010"});
  xhr.send(data);
 }
 function createRadioElement(name, checked) {
  var radioHtml = '<input type = "radio" name="' + name + '"';
  if ( checked ) {
  radioHtml += ' checked="checked"';
  }
  radioHtml += '/>';

  var radioFragment = document.createElement('div');
  radioFragment.innerHTML = radioHtml;

 return radioFragment.firstChild;
 }




Aucun commentaire:

Enregistrer un commentaire