4

When I implement this code - the name of the checkbox wont show up in the browser alongside the checkbox - just the checkbox itself. whats the reason for this? Am I using the setattribute-function incorrectly?

<script type="text/javascript">

    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "car");
    x.setAttribute("name", "vehicle");
    document.body.appendChild(x);

</script>
java
  • 1,165
  • 1
  • 25
  • 50

2 Answers2

4

You need to add a label element:

var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("value", "car");
x.setAttribute("name", "vehicle");
document.body.appendChild(x);

var label = document.createElement("label");
label.textContent = "vehicle";
document.body.appendChild(label);
Luka
  • 2,779
  • 3
  • 17
  • 32
  • A [*label*](http://w3c.github.io/html/sec-forms.html#the-label-element) is associated with a form control either by using an ID on the form control and a *for* attribute on the label, or wrapping the label around the control. Simply placing the label adjacent to the control is the same as just using a span or plain text node. – RobG May 15 '16 at 20:56
1

You should create a label for the check box as you created checkbox dynamically and append it to body

    //create checkbox
    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "car");
    x.setAttribute("name", "vehicle");

    //create label
    var y = document.createElement("label");
    y.innerHTML = "Here goes the text";

    //Append Them to body
    document.body.appendChild(x);
    document.body.appendChild(y);
Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55