Search code examples
javascripthtmlradio-button

Dynamically Creating HTML with Javascript not working


No JQuery. I am trying to create a radio button followed by text with javascript. It is printing out everything after the document.writes. I think I have a problem with the quotes, but I can't fix it. Can someone help me fix this?

function printarray (newarray, cnt) { 
  if (cnt < 2) { 
        document.getElementById('radio').style.display = 'none'; 
  } else { 
    for (var i = 0; i < newarray.length; i++) { 
      var cur_text = newarray[i]; 
      if (i == 0) { 
        var radio = '<input type="radio" name="bank" value="KeyBank" onclick="showChoice(this)">' + 'KeyBank'; 
      } else { 
        radio = radio + '<input type="radio" name="bank" value="<script>document.write(cur_text);</script>" onclick="showChoice(this)">' + "<script>document.write(cur_text)</script>;"; 
      } 
    } 
    document.getElementById('btn').style.display = 'none'; 
    var foo = document.getElementById('radio').innerHTML = radio; 
  } 
  document.getElementById('array').innerHTML = cnt; 
} 

Solution

  • First issue is, below line is wrong,

    radio = radio + '<input type="radio" name="bank" value="<script>document.write(cur_text);</script>" onclick="showChoice(this)">' + "<script>document.write(cur_text)</script>;";
    

    Corrected line,

    radio = radio + '<input type="radio" name="bank" value="'+cur_text+'" onclick="showChoice(this)">' + cur_text;