java java - 6 months ago 32
Javascript Question

Javascript setattribute - name and value not work

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>

Answer

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);
Comments