admin管理员组

文章数量:1287593

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.

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.

Share Improve this question asked Oct 29, 2014 at 9:36 user2656098user2656098 3
  • w3/wiki/Creating_and_modifying_HTML – Quentin Commented Oct 29, 2014 at 9:37
  • Could you explain better "with name and value depending on the former created object"? Otherwise document.createElement will be the way – Rikard Commented Oct 29, 2014 at 9:37
  • var i = document.createElement('input'); i.type='checkbox'; – pawel Commented Oct 29, 2014 at 9:38
Add a ment  | 

3 Answers 3

Reset to default 6

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

本文标签: How to create a new HTML checkbox via JavaScriptStack Overflow