How can I append a checkbox input wrapped by the 'li'? - javascript

I managed to input the 'li' inside the 'ul', but I need to have a checkbox input inside the li, and I can't seem to figure how.
<body>
<div class="card">
<h1>To-do list</h1>
<input type="text" id="taskInput" placeholder="Digite aqui sua tarefa">
<button id="add">Adicionar</button>
<ul id='tasks'>
<li><input type="checkbox"> Tarefa 1</li>
</ul>
</div>
<script>
document.getElementById('add').onclick = function add() {
const val = document.querySelector('input').value;
const ul = document.getElementById('tasks');
let li = document.createElement('li');
li.appendChild(document.createTextNode(val));
ul.appendChild(li);
};
</script>
</body>

Try to create element input and specify the type to checkbox and added it to created element li first, then add the text value of input also lastly append it to ul:
document.getElementById("add").onclick = function () {
const val = document.querySelector("#taskInput").value; //specify the selector
const ul = document.getElementById("tasks");
let li = document.createElement("li");
let input = document.createElement("input"); //add Input
input.type = "checkbox"; //specify the type of input to checkbox
li.appendChild(input);
li.appendChild(document.createTextNode(val));
ul.appendChild(li);
};
<div class="card">
<h1>To-do list</h1>
<input type="text" id="taskInput" placeholder="Digite aqui sua tarefa" />
<button id="add">Adicionar</button>
<ul id="tasks">
<li><input type="checkbox" /> Tarefa 1</li>
</ul>
</div>

you just need to set type as a checkbox.
document.getElementById('add').onclick = function add() {
var input = document.createElement("INPUT");
input.setAttribute("type", "checkbox");
const ul = document.getElementById('tasks');
let li = document.createElement('li');
li.appendChild(document.createTextNode(input));
ul.appendChild(li);
};

After you have created li, just append a checkbox child to it:
let chk = document.createElement('input');
chk.setAttribute('type', 'checkbox');
li.appendChild(chk)

Same way as the other elements, just as an input of type 'checkbox'
Also for accessibility purposes, it would be better to use a label instead of a text node.
const val = document.querySelector('input').value;
const ul = document.getElementById('tasks');
let li = document.createElement('li');
let checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = 'tasks-' + val;
checkbox.value = val;
checkbox.setAttribute('name', 'tasks');
let label = document.createElement('label');
label.htmlFor = checkbox.id;
label.innerText = val;
li.appendChild(checkbox);
li.appendChild(label);
ul.appendChild(li);

you can use this code
<script>
document.getElementById('add').onclick = function add() {
const val = document.querySelector('input').value;
const ul = document.getElementById('tasks');
let li = document.createElement('li');
let input = document.createElement('input');
input.type='checkbox'
li.appendChild(input)
li.appendChild(document.createTextNode(val));
ul.appendChild(li);
};
</script>

*This method is faster and cleaner*
<script>
document.getElementById('add').onclick = function add() {
const ul = document.getElementById('tasks');
const val = document.querySelector('input').value;
ul.innerHTML += `<li>${val}</li>`;
};
</script>

Related

I am trying to prevent my delete icon from getting the strike-through function when applied to 'LI' elements

I've tried to get the strike-through just in the "LI" elements, but what happened was the "TRASH" icon is taking this strike-through as well as shown in the screenshot below,
let input = document.querySelector('#todo');
let btn = document.querySelector('#btn');
let button = document.querySelector('#Clear-all')
let list = document.querySelector('#list');
let el = document.getElementsByTagName('li');
const deleteButton = document.getElementsByTagName("i");
// let's add the elements
function Items() {
btn.addEventListener('click', () => {
let text = input.value;
if (text === "") {
alert('You must add something in the field below');
} else {
let li = document.createElement("li");
li.innerHTML = text;
list.insertBefore(li, list.childNodes[0]);
input.value = "";
var createDeleteButton = document.createElement("i");
createDeleteButton.classList.add("fa", "fa-trash");
li.appendChild(createDeleteButton);
createDeleteButton.addEventListener('click', function() {
li.innerHTML = "";
})
}
})
}
Items();
// to add a strike through done
list.addEventListener('click', e => {
if (e.target.tagName === 'LI') {
e.target.classList.toggle('done');
}
});
<div class="add-element">
<input type="text" id="todo" placeholder="Type anything">
<button id="btn">Add</button>
<button id="Clear-all">Clear List</button>
</div>
<div class="element-list">
<div id="div">
<ul id="list">
<li id="items"></li>
</ul>
</div>
</div>
What you'r looking for is Event.stopPropagation()
createDeleteButton.addEventListener('click', function(event){
event.preventDefault(); // <= Not sure if you need this one, just for precaution
event.stopPropagation();
li.remove();
})
Edit :
list.addEventListener('click', ... is on the ul element so it will affect all the elements inside the ul, all the li including the delete button i, where ever you click inside the ul the event will be triggered, I made some change to your code, removed the ul event, add a checkbox for each element with an event listener, in order for your li elements to be stroke through individually.
let input = document.querySelector('#todo');
let btn = document.querySelector('#btn');
let clear = document.querySelector('#Clear-all')
let list = document.querySelector('#list');
let el = document.getElementsByTagName('li');
// let's add the elements
function Items() {
btn.addEventListener('click', () => {
let text = input.value;
if (text === "") {
alert('You must add something in the field below');
} else {
// Create Item
let li = document.createElement("li");
list.insertBefore(li, list.childNodes[0]);
input.value = "";
// Create a text container element
const textContainer = document.createElement('b');
textContainer.innerText = text;
li.appendChild(textContainer);
// Add a delete button
const deleteButton = document.createElement("i");
deleteButton.classList.add("fa", "fa-trash");
deleteButton.innerText = "X"; // <= Remove this line if you want to remove the X
li.appendChild(deleteButton);
deleteButton.addEventListener('click', function() {
li.remove();
});
//Add a checkbox for the strike through
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
deleteButton.classList.add("fa", "fa-trash");
li.prepend(checkbox);
checkbox.addEventListener('change', function() {
if(checkbox.checked) li.classList.add("done");
else li.classList.remove("done");
});
}
})
}
Items();
// Cear all function
clear.onclick = () => {
list.innerHTML = "";
}
.done b{
text-decoration: line-through;
}
i {
color: red;
padding: 0 10px;
cursor: pointer;
}
<div class="add-element">
<input type="text" id="todo" placeholder="Type anything">
<button id="btn">Add</button>
<button id="Clear-all">Clear List</button>
</div>
<div class="element-list">
<div id="div">
<ul id="list">
</ul>
</div>
</div>

I want to add space between an li element i created using DOM selectors and the button element created along side it

How can i add space between the an li element created and the button element created?
function createListElement(){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
ul.appendChild(li);
input.value = "";
li.addEventListener("click", linecross);
}
jut add some margin left to button
function createListElement(){
var li = document.createElement("li");
var input =document.getElementsByTagName('input')[0];
var ul =document.getElementsByTagName('ul')[0];
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
ul.appendChild(li);
input.value = "";
li.addEventListener("click", linecross);
}
function linecross(){
console.log('linecross');
}
createListElement();
button{
margin-left:200px;}
<input value=5/>
<ul></ul>
Using the style property you can solve it in css
function createListElement(){
var input = {value:'random text'};
var ul = document.querySelector('ul');
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
li.classList.add("space")
var Delete = document.createElement("button");
Delete.innerHTML="Delete";
li.appendChild(Delete);
Delete.addEventListener("click",function(e){
this.parentNode.parentNode.removeChild(this.parentNode);
})
Delete.style.marginLeft = '10px';
ul.appendChild(li);
input.value = "";
li.addEventListener("click", function(){});
}
createListElement()
<html>
<head></head>
<body>
<ul></ul>
</body>
</html>

Unable to remove checkbox with JavaScript

Actually, I want to remove a specific checkbox div from at any time.
As trying to give a functionality that a user can add or remove a checkbox perfectly.
I wrote the code I try to add or rest the check box but when I try to remove the checkbox it does not work and I am not figuring out what is the problem.
Can someone fix it?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
li.appendChild(div);
ul.appendChild(li);
}
function addElement(elementId, html) {
// Adds an element to the document
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
}
var checkId = 0;
function addcheck() {
checkId++; // increment fileId to get a unique ID for the new element
var html = 'Remove';
addElement( checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem , addcheck() ;
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItems , addFile() ">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
here is the working code ok Eddie ?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(linkElement) {
// Removes an element from the document
var element = linkElement.parentNode.parentNode;//to get to the li element
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
addcheck(div)
li.appendChild(div);
ul.appendChild(li);
}
function addElement(div,elementId, html) {
// Adds an element to the document
div.setAttribute('id', elementId);
div.innerHTML += html;
}
var checkId = 0;
function addcheck(div) {
checkId++; // increment fileId to get a unique ID for the new element
var html = '<a class="link" href="" onclick="javascript:removeElement( this ); return false;">Remove</a>';
addElement( div, checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem ;
add this css for just readability but i think you will add more to the css
<style>
.link{
padding-left: 10px;
}
</style>
There is a way to do it with a single function:
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<div>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItem()">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
</body>
</html>
<script type="text/javascript">
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
var checkId = 0;
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
li.id = checkId;
removeLink = 'Remove';
checkId++;
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
div.innerHTML+=removeLink;
li.appendChild(div);
ul.appendChild(li);
}
</script>

How to set localStorage in Javascript

This is a to do list program. I want to save my to do list page when the page is refreshed. All the css and other functions work properly. I think my mistake is using the wrong variable within the store function My current attempt still isn't working. The attempt is at the end of the script. What did I do wrong?
var inputItem = document.getElementById("inputItem");
inputItem.focus();
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
label.appendChild(checkBox);
label.appendChild(labelText);
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
function store() {
var html = listItem.innerHTML;
localStorage.setItem("page", html);
}
function retrieve() {
var html = localStorage.getItem("page");
listItem.innerHTML = html;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<h1 align="center"> To-Do List </h1>
<body>
<div id="outerDiv">
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>
</div>
<div id="innerDiv">
<ul id="list"></ul>
</div>
</body>
</html>
I think you have to store only value instead of whole html.
var inputItem = document.getElementById("inputItem");
inputItem.focus();
function addItem(list, value, onLoad) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = value;
label.appendChild(checkBox);
label.appendChild(labelText);
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
if(!onLoad) {
this.store(value);
}
return false;
}
function store(value) {
var list = localStorage.getItem("list");
if(list) {
list = list.split(",");
list.push(value); ;
} else {
list = [value];
}
localStorage.setItem("list", list.toString());
}
window.onload = function() {
var list = localStorage.getItem("list");
if(list) {
list = list.split(",");
list.forEach(function(li){
this.addItem("list", li, true);
},this);
}
}
And You have to change your html
<form onsubmit="return addItem('list', this.inputItem.value)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>

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);
}

Categories