Trying to create a todo list with delete function - javascript

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.

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>

HTML Javascript dynamically add and remove textboxes

I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}

todo list- trying to add inputs to an array/doesnt work

I am building a small todo list and want to do the following: each text input (or actually a copy of the text input) should be added to an empty string (copy because it should not disappear when added). Then I have a function which is called when user clicks on a button and then I want to pick a random todo thing.
I didn't even get to the point when I pick out a random todo thing because my code just doesn't work- It seems like the adding does happen, but instead of adding a todo thing, thats being added:[object HTMLInputElement]
Anyone has an idea?
My javascript code:
var totalItems=0;
var listOf="";
function randomItem(){
document.getElementById("randomArray").innerHTML=listOf;
}
function updatingItem() {
var cbId = this.id.replace("cb_", "");
var textItem = document.getElementById("item_" + cbId);
if (this.checked) {
textItem.style.textDecoration = "line-through";
textItem.style.background="pink";
}
else {
textItem.style.textDecoration = "none";
textItem.style.background="white";
}
}
function addItem() {
totalItems++;
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "cb_" + totalItems;
checkBox.onclick = updatingItem;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.innerHtml = textItem;
var textItem = document.getElementById("textItem");
span.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
var listOfItems=textItem;
listOf+=listOfItems;
}
var item = document.getElementById("add");
item.onclick = addItem;
document.getElementById("lastButton").onclick=randomItem;
HTML:
<body>
<div class="table">
<h1>To Do List</h1>
</div>
<p>
<input type="text" id="textItem"/>
<button id="add"><b>Add</b></button>
</p>
<ul id="todoList"></ul>
<h3>Pick a random to do thing to do for today</h3>
<button id="lastButton">Go!</button>
<p id="randomArray"></p>
</body>
Your randomItem() function is working incorrectly, as you are trying to create String from Object directly while using listOfItems. Either use its value or try using following code instead for proper view. Also add one list element in HTML with id="myList". IT will work fine.
JS:
function randomItem(){
var counter = 0;
var textItems = document.getElementsByTagName("input");
var done = [];
for (var i=0; i<textItems.length; i++)
{
if(textItems[i].type == "checkbox")
{
if(textItems[i].checked)
{
document.getElementById("item_"+i);
done.push(document.getElementById("item_"+i).innerHTML);
var list = document.getElementById('myList');
var data = document.createElement('li');
data.appendChild(document.createTextNode(done[counter]));
counter++;
list.appendChild(data);
}
}
}
}
HTML:
<ol id = "myList"></ol>
try
var listOfItems=textItem.value;
rather than
var listOfItems=textItem;

Change the color of text with a dynamic checkbox

I'm working on a to do list. I can enter text within a field and create a new item with a checkbox, but I cannot get the checkbox to do anything. I would like to change the color of the text once the checkbox has been clicked
function todoadd() {
todoNew = new objectTodo();
}
function objectTodo() {
var todo = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(todo);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
function changeColor(checkbox,itemText) {
var check = document.getElementById(checkbox);
var todoItem = document.getElementById(itemText);
if (check.checked == true) {
todoItem.style.backgroundColor="Red";
}
}
}
<title>ToDo</title>
<body>
<div id="container">
<div id="todoList">
<div id="textboxBackground">
<input type='text' id='textinput' placeholder='What do you need to do today?' />
<button type='button' id="myButton" class='button' onclick='todoadd()' value='Add to list' />Add To-do</button>
</div>
<ul id="place"></ul>
</div>
You need to bind event to all the checkboxes. Something like following-
var checkboxes = document.querySelector('checkbox');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].change(function() {
var text = this.parentNode.childNodes[]; // select the textnode here by giving the index to childNodes. Should be 0 or 1.
if (this.checked == true) {
text.style.backgroundColor="Red";
}
else {
text.style.backgroundColor="grey"; // set the original color here
}
});
}

dynamically add event listener for function with variable

I am trying to create an option to add additional checkboxes/text fields to my website. I have a button "+" linked to a function that creates the fields named in numerical order. I would like to add an event listener to the checkbox that will call a function that requires a unique variable, based on the name of the checkbox that called it.
<div id="container">
<input name="+" type="button" id="+" onclick="addInput()" value="+" label="+" />
</div>
<p id=demo>eeeeeeee</p>
var countBox = 1;
function addInput () {
var breakNode = document.createElement("br");
breakNode.className = countBox.toString();
//create checkbox
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = "ProgramSpecificBox" + countBox.toString();
checkbox.name = "ProgramSpecificBox" + countBox.toString();
checkbox.id = "ProgramSpecificBox" + countBox.toString();
//create Amount
var Amount = document.createElement("input");
Amount.type = "number";
Amount.value = countBox.toString();
Amount.name = "ItemCostVis"+ countBox.toString();
Amount.id = "ItemCostVis" + countBox.toString();
var container = document.getElementById('container');
container.appendChild(breakNode);
container.appendChild(checkbox);
container.appendChild(Amount);
checkbox.addEventListener("click", function () {
testthis(NEED CODE HERE);
})
countBox += 1;
}
function testthis (text) {
document.getElementById("demo").innerHTML = text;
}
What should I put instead of "NEED CODE HERE" to get the same as the id of the checkbox that called the function?
Instead of:
checkbox.addEventListener("click", function()
{testthis(NEED CODE HERE);
})
countBox += 1;
}
try:
checkbox.addEventListener("click", function(e)
{testthis(e);
})
countBox += 1;
}
the e parameter should be the event object. An event object has a property currentTarget, which references the element that initialised the event. Therefore you can call:
function testthis(e)
{
var myvar = e.currentTarget.id;
}
See this fiddle for an example.
You can try something like this:
checkbox.onclick = function(me){window.alert(me.id)};

Categories