0

I am trying to add a radio/checkbox inside the .innerHTML for a program in JavaScript. Is there a way to add a radio box/checkbox inside a .Innerhtmljavascript codes Innerhtml part:

document.getElementById("demo").innerHTML = "I need a radiobox here";
Pang
  • 9,564
  • 146
  • 81
  • 122

3 Answers3

0

You just need to pass the html code for the radio button..

document.getElementById('demo').innerHTML = '<input type="radio" />'
0

document.getElementById("demo").innerHTML = "<input id='radiobutton' type='radio' >text</input>";
<div id="demo" >
  
</div>
Ali Heidari
  • 3
  • 2
  • 5
  • Thanks A Ton I tried the same thing but did not know how that a " " was needed for the code..again thanks –  Sep 17 '16 at 01:16
0

instead of innerHTML, a better way to insert a new element into your Document

Element.appendChild

var radio = document.createElement("input");
radio.type = "radio";
radio.name = "r1";
document.querySelector("#demo").appendChild(radio);
<label id="demo"></label>

Element.insertAdjacentHTML

document.querySelector("#demo").insertAdjacentHTML(
  "beforeend",
  "<input type='radio' name='r1'>"
);
<label id="demo"></label>

Available insertion points: 'beforebegin' 'afterbegin' 'beforeend' 'afterend'

innerHTML will rewrite your target Element content, losing previous input states and attached events etc. Read more here

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313