简体   繁体   中英

How to create a new HTML checkbox via JavaScript?

I have defined a button in HTML which calls a function to create an object in my JS. In addition, i would like this button to "spawn" the creation of a new checkbox (with name and value depending on the former created object) in HTML, lets say in div id XY.

Though i suppose it's not important, here is my current stuff.

html

<input id="button" value="pick Brakiri" onclick="initiate('Brakiri')">

js

function initiate(faction){
calc = new Calc(faction)
}

I would like to avoid jQuery if possible.

thank you.

You should create a functin for this. A example under where you pass in name and id and it returns a brand new element:

function createNewCheckboxt(name, id){
    var checkbox = document.createElement('input'); 
    checkbox.type= 'checkbox';
    checkbox.name = name;
    checkbox.id = id;
    return checkbox;
}

After you just need to choose where to add it into the DOM. Something like:

form.appendChild(createNewCheckboxt('theName', 'theID'));

Hi i'm not sur if i understand your question but this the code to create a new checkbox via javascript :

var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";    
container.appendChild(checkbox);

You can create an <input> element with type="checkbox" by using the document.createElement() method.

This will work:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to create a Checkbox.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "abc");
    x.setAttribute("name", "xyz");

    document.body.appendChild(x);
}
</script>

</body>
</html>

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM