create checkboxes dynamically in JavaScript - javascript

I'm trying to create check boxes dynamically. But I have no idea what is the wrong with this code. Somebody please help. Comment if you need more details.
$.getJSON(url, function(json) {
console.log(json);
console.log(json.items.length);
for (var i = 0; i < json.items.length; i++) {
console.log(json.items[i].name);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name" + json.items[i].name;
checkbox.value = "value";
checkbox.id = "id" + i;
}
});
Thank you

You never seem to be appending those dynamically created checkboxes to your DOM, so this checkbox variable that you create inside the loop simply gets garbage collected. If you want those checkboxes to appear somewhere make sure that you are actually adding them to the DOM:
document.body.appendChild(checkbox);
Of course instead of simply appending them to the body of the DOM you might want to append them to some specific element in which case you might need to get this element first:
var someDiv = document.getElementById('someId');
someDiv.appendChild(checkbox);
or if you are using jQuery:
for (var i = 0; i < json.items.length; i++) {
$('<input />', {
type : 'checkbox',
id: 'id' + i,
name: 'name' + json.items[i].name,
value: 'value'
})
.appendTo("#someId");
}
where you obviously have the corresponding container to harbor those newly added elements:
<div id="someId"></div>

Just what Darin said,
you need to append a dynamically created element to the DOM. So in your case
$.getJSON(url, function(json) {
console.log(json);
console.log(json.items.length);
for(var i=0;i<json.items.length;i++){
console.log(json.items[i].name);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name"+json.items[i].name;
checkbox.value = "value";
checkbox.id = "id"+i;
document.body.appendChild(checkbox);
}
});
OR You can create a div in your HTML sheet, and append your checkboxes to that, so it would be something like ..
var div = document.getElementById('div');
for(var i=0;i<json.items.length;i++){
console.log(json.items[i].name);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name"+json.items[i].name;
checkbox.value = "value";
checkbox.id = "id"+i;
div.appendChild(checkbox);
}
});

you need to add the checkbox in some html container. say you have a div with id append like below,
<div id="append" name="append">Append here</div>
and your dynamically created checkbox added to that div.
js:
$.getJSON(url, function(json) {
console.log(json);
console.log(json.items.length);
for (var i = 0; i < json.items.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name" + json.items[i].name;
checkbox.value = "value";
checkbox.id = "id" + i;
document.getElementById( 'append' ).appendChild( checkbox);
}
});

Related

How to populate a checkbox list in HTML from a JavaScript array [duplicate]

I have an array of animals ... how do I manage to create a checkbox list in javascript and fill each with a name of the animals who are in animals array and display them in html.
My my attempt code:
var lengthArrayAnimals = animals.length;
for (var i= 0; pos < tamanhoArrayDiagnosticos; pos++) {
var checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkbox");
checkBox.name = diagnosticos[i];
}
Here's one way (pure JavaScript, no jQuery):
var animals = ["lion", "tigers", "bears", "squirrels"];
var myDiv = document.getElementById("cboxes");
for (var i = 0; i < animals.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = animals[i];
myDiv.appendChild(checkBox);
myDiv.appendChild(label);
label.appendChild(document.createTextNode(animals[i]));
}
https://jsfiddle.net/lemoncurry/5brxz3mk/
I hope this is what you expected.
$(document).ready(function(){
var animals=["cat","dog","pikachu","charmaner"];
$.each(animals,function(index,value){
var checkbox="<label for="+value+">"+value+"</label><input type='checkbox' id="+value+" value="+value+" name="+value+">"
$(".checkBoxContainer").append($(checkbox));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="checkBoxContainer"></div>

How to add a line break after each dynamically created checkbox?

Here's the code for the dynamically created checkboxes. How do I add line breaks to the code so that I have one checkbox per line? I tried to do document.createElement("br") and appending it after get.appendChild(label) but it didn't work.
function setCheckboxes(browser) {
var get = document.getElementById("get");
if (browser == "courses") {
for (var i = 1; i < coursesGetKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = coursesGetKeys[i];
checkBox.name = "r";
label.textContent = setOpt(coursesGetKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}
if (browser == "rooms") {
for (var i = 1; i < validRoomsKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = validRoomsKeys[i];
checkBox.name = "r";
label.textContent = setOpt(validRoomsKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}
};
You already know how to create an input:
var checkBox = document.createElement("input");
and how to append it:
get.appendChild(checkBox); // get is the parent element you selected at the top of your code
So your first hunch was correct, you can also do this:
var br = document.createElement("br");
get.appendChild(br);
which creates a br element, and then also appends it to the "get" parent.

Trying to create a todo list with delete function

Im new to javascript and coding in general, I'm trying to make a simple to do list but cant get the delete button to delete all the checkboxes, it will only delete the first checkbox made. Thanks guys.
http://jsfiddle.net/fbct3oL7/1/
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
listItem.id = task;
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
checkbox.name = task;
checkbox.id = "checkbox";
document.getElementById('place').appendChild(listItem);
document.getElementById(task).insertBefore(checkbox, listItem.firstChild);
}
function deleteCheckBox() {
while (document.getElementById('checkbox').checked === true) {
var itemNode = document.getElementById(checkbox.name);
itemNode.parentNode.removeChild(itemNode);
}
}
I've modified your code, eliminating unnecessary id and name attributes, and updated the deleteCheckBox function to cycle through all the li in the ul.
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
}
function deleteCheckBox() {
var ul = document.getElementById('place');
var li = ul.children;
for (var i=0; i < li.length; i++) {
while(li[i] && li[i].children[0].checked) {
ul.removeChild(li[i]);
}
}
}
<div id="list">
<input type='text' id='textinput' />
<input type='button' onclick='taskadd()' value='Add to list' />
<input type='button' onclick="deleteCheckBox()" value='Delete' />
<ul id="place"></ul>
</div>
I also forked and updated your Fiddle: http://jsfiddle.net/JohnnyEstilles/gtpdLkLq/.
You give every checkbox the same id, and the getElementById method only returns the first matching element.
If you want to get all checkboxes and delete the checked ones you could start by doing like this. (Please notice that this code is written freehand and untested)
var inputs = document.getElementsByTagName("input");
for(i=o; i < inputs.length; i++){
if(inputs[i].type == "checkbox" && inputs[i].checked){
inputs[i].parentNode.removeChild(inputs[i]);
}
}
First get all element with the tag "input", then check if they are of checkbox type and checked.

Checkbox label is being displayed on next line

I have a checkboxlist, and I created a javascript function that will add checkbox to the checkboxlist,
here's the code
function add1()
{
var ques = document.getElementById('Questions_que1');
var container = document.getElementById('Questions_wh1');
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "que1";
checkbox.value = ques.value;
checkbox.id = "id";
var label = document.createElement('label');
label.htmlFor = "id";
label.appendChild(document.createTextNode(ques.value));
container.appendChild(checkbox);
container.appendChild(label);
}
but the problem is that the checkbox label is being displayed on the next line instead of after the checkbox on the same line..
what am I doing wring here???

Javascript -> Attempting to dynamically add radio buttons from an array

So I'm working on my very first 'real' JavaScript project -> the famed Quiz app :)
I'm passing questions and answers via an array, and I want make sure to allow for a variable number of answer options. To do this, I'm using a For loop and the createElement method to add and populate the appropriate HTML for each answer in the array. To my eyes, what I've built actually works great. And after running the function I can see the resultant HTML elements in the right place and with all the appropriate tagging in my console. However, the inner DIV text won't render on screen! Very confused. What am I missing? Please help!
My JS code:
<body>
<form id="form1">
</form>
<script>
var answers = ["answer1", "answer2", "answer3", "answer4", "answer5"];
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("form1");
for (var i = 0; i < len; i++){
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
form.appendChild(radio);
radio.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
}
}
</script>
</body>
And here's a screenshot of my console AFTER I run the function, for reference:
You're plan is nearly working but Input elements have no content! So the div's will not be rendered at all!
Create a div that contains your radio button and the input text on the same level:
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
radioText.innerHTML = array[i];
radioText.appendChild(radio);
form.appendChild(radioText);
Add label after or before radio button. Label will let you check radio button by clicking on it's text
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("label");
radioText.id = "c" + i;
radioText.setAttribute("for", "choice" + i);
radioText.class = "choiceText";
form.appendChild(radio);
form.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
<input> cannot contain any DOM elements or DOM nodes. But if you want to have checkboxes associated with some text, I suggest you to use <input> with <label for=""> where label.for is name of input element. For combining them you can put them into some container(i.e. <div>):
By default on label with set property for raises click event on element with the same name property value as for property value. This means that you do not need to add additional click event handlers for <label> elements.
var checkId = 1;
var container = document.createElement("div");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices"+checkId;
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var label = document.createElement("label");
label.innerHTML = array[i];
// Set attribute for
label.setAttribute("for","choices"+checkId);
//Increase counter for check element name.
checkId++;
container.appendChild(radio);
container.appendChild(label);
form.appendChild(container);

Categories