Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 928
java Avatar asked May 15 '16 20:05

java


People also ask

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).

How does setAttribute work in JavaScript?

setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .

Does setAttribute overwrite?

setAttribute('style', 'property: value'); And it works, but if that element already had styles applied, they will all get overwritten.

How do you set a disabled attribute?

To set the disabled attribute, select the element and call the setAttribute() method on it, passing it disabled as the first parameter, e.g. button. setAttribute('disabled', '') . The setAttribute method will add the disabled attribute to the element. Here is the HTML for the examples in this article.


1 Answers

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);
like image 184
Luka Avatar answered Nov 02 '22 08:11

Luka