How to set localStorage in Javascript - 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>

Related

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

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>

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 add an element on top of another element that have been dynamically created in javascript

I have a button allowing to display more fields in order to get supplementary information about a user(his address & his email).
well, when I click on the button it adds the fields, the trouble is with their positions, I want it to be above the button not below it
here is the code
<html>
<head>
<script>
function addUser() {
let position2 = document.getElementById("position2");
var name = document.createElement("label");
position2.appendChild(document.createTextNode("name"));
var inputName = document.createElement("input");
inputName.setAttribute("type", "text");
position2.appendChild(inputName);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "add informations");
btn.setAttribute("onclick", "showMore()");
position2.appendChild(btn);
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
}
function showMore() {
var adress = document.createElement("label");
position2.appendChild(document.createTextNode("adress"));
var inputAdress = document.createElement("input");
inputAdress.setAttribute("type", "text");
position2.appendChild(inputAdress);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var email = document.createElement("label");
position2.appendChild(document.createTextNode("email"));
var inputEmail = document.createElement("input");
inputEmail.setAttribute("type", "text");
position2.appendChild(inputEmail);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
}
</script>
</head>
<body>
<form id="form">
<div id="position2"></div>
<button type="button" onclick="addUser()"> click to add user </button> <br><br>
</form>
</body>
</html>
You can use insertBefore instead of appendChild. It takes a second argument, which in your case should be the button element.
In order to get a reference to the button, I would associate the button's click handler via script, not via the onclick attribute. Then the handler will get the event object, which has the button in its target property.
See below for the changes:
<html>
<head>
<script>
function addUser() {
let position2 = document.getElementById("position2");
var name = document.createElement("label");
position2.appendChild(document.createTextNode("name"));
var inputName = document.createElement("input");
inputName.setAttribute("type", "text");
position2.appendChild(inputName);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "add informations");
btn.onclick = showMore; // <----
position2.appendChild(btn);
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
}
function showMore(e) { // <--- argument
var btn = e.target; // <--- get button
var adress = document.createElement("label");
// call insertBefore with second argument
position2.insertBefore(document.createTextNode("adress"), btn);
var inputAdress = document.createElement("input");
inputAdress.setAttribute("type", "text");
position2.insertBefore(inputAdress, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
var email = document.createElement("label");
position2.insertBefore(document.createTextNode("email"), btn);
var inputEmail = document.createElement("input");
inputEmail.setAttribute("type", "text");
position2.insertBefore(inputEmail, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
btn.setAttribute('disabled', 'disabled');
}
</script>
</head>
<body>
<form id="form">
<div id="position2"></div>
<button type="button" onclick="addUser()"> click to add user </button> <br><br>
</form>
</body>
</html>

what actually does this keyword in javascript works?

Actually i am beginner in javascript and i am making a todo list with only javascript and given is my code..
function updateItemStage() {
var cbId = this.id.replace("cb_", "");
var itemText = document.getElementById("Item_" + cbId);
if (this.checked) {
itemText.className = "checked";
} else {
itemText.className = "";
}
}
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
checkBox.id = "cb_" + totalItems;
var span = document.createElement("span");
span.innerHTML = itemText;
span.id = "Item_" + totalItems;
listItem.appendChild(checkBox);
listItem.appendChild(span);
list.appendChild(listItem);
}
var totalItems = 0;
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var todoInput = document.getElementById("todoInput")
var itemText = todoInput.value;
if(!itemText || itemText == "") {
return false;
}
addNewItem(document.getElementById("todolist"), itemText);
};
Using this code i successfully create a todo list but in this code i didn't get what is the main role and work of this keyword..
can anyone help me please to understand this problem ???????????
The this keyword is the element where your event happens
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
In your case, this is the checkBox which you clicked.

how to remove an object by button?

i built two buttons with this values("+" and "-")
when i click on "+" it creates a text and combo box,
i wanna know how to remove them with "-" button?(by only JavaScript)
here's the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>create and delete</title>
<script type="text/javascript">
/*this function creates text box and combo box*/
function cre()
{var t=document.createElement('select');
var form=document.getElementById('theForm');
var label = document.createElement('label');
var textbox = document.createElement('input');
form.appendChild(t);
form.appendChild(textbox);}
function del()
/*{delete t,form,label,textbox;}*/
</script>
</head>
<body>
<form id='theForm'>
<input type="button" value="+" onclick="cre()" />
<input type="button" value="-" onclick="del()" />
</form>
</body>
</html>
function del()
{
var form=document.getElementById('theForm');
var t = form.getElementsByTagName('select');
var textbox = form.getElementsByTagName('input');
if(t != 'undefined' && textbox != 'undefined')
{
form.removeChild(t[t.length-1]);
form.removeChild(textbox[textbox.length-1]);
}
}
Fiddle for your reference
My solution :
cre = function() {
var form = document.getElementById('theForm'),
div = document.createElement('div'),
t = document.createElement('select'),
label = document.createElement('label'),
textbox = document.createElement('input');
div.className = 'divContainer';
div.appendChild(t);
div.appendChild(label);
div.appendChild(textbox);
form.appendChild(div);
}
/*{delete t,form,label,textbox;}*/
delForm = function() {
var form = document.getElementById('theForm');
form.parentNode.removeChild(form);
}
del = function() {
var containers = document.getElementsByClassName('divContainer');
for(var i = 0; i < containers.length; i++) {
if(typeof(containers[i]) === 'object') {
containers[i].parentNode.removeChild(containers[i]);
}
}
}
JSFiddle : http://jsfiddle.net/j6Fxc/27/

Categories