How to add user prompt input to an array permenantly - javascript

So I'm trying to add a prompt which asks the user what they would like to add to an array. However, whenever I refresh the page, it gets deleted like it is only in local storage. I would like to add this to the actual code so it gets displayed permanently within the page.
Here is the relavent code:
<html>
<body>
<div class="ann" id="shadowbox">
<h4>Latest Announcements</h4>
<ul id="myUl"></ul>
</div>
<button onclick="fc()">populate</button>
<script>
var announcements = ["test",]
for (i = 0; i < announcements.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(announcements[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
function fc() {
var asdkz = prompt("What would you like to add?")
announcements.push(asdkz);
}
</script>

You need to use localStorage to save the content of the array after refresh. Here is the solution with some modification:
<html>
<body>
<div class="ann" id="shadowbox">
<h4>Latest Announcements</h4>
<ul id="myUl"></ul>
</div>
<button onclick="fc()">populate</button>
<script>
var announcements = (localStorage.getItem("list")) ? localStorage.getItem("list").split(",") : ["test"]
updateList();
function updateList(){
document.getElementById("myUl").innerHTML = "";
for (i = 0; i < announcements.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(announcements[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
}
function fc() {
var asdkz = prompt("What would you like to add?")
announcements.push(asdkz);
localStorage.setItem("list",announcements);
updateList();
}
</script>

Related

How to do local storage for to-do list?

I am currently working on making the to-do list app shown [here][1] work better. I have done things like change the font, but want to use Javascript cookies to make it so that the user's to-dos are properly saved and still there when the page is reopened.
All I need now (which I can't seem to get the idea of how to do) is the part where 1. the browser saves the data and 2. where the browser retrieves the data.
Any help would be greatly appreciated.
<body>
<!--To-Do Header, where you add tasks-->
<div id="myDIV" class="header">
<!--Change one: Make to-do list name different-->
<h2>To-Do</h2>
<input type="text" id="myInput" placeholder="Title..." style="padding-bottom: 20px;">
<span onclick="newElement();" class="addBtn">Add</span>
</div>
<!--To-do list-->
<ul id="myUL">
</ul>
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
};
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something to create a task.");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
};
}
}
Using local storage, as it lasts longer then cookies:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
EDIT: #MichaelMior pointed out that local storage may not last longer then cookies, but the cookies are sent with browser requests so it's unnecessary in this case.
You want to store the text content, so you need to get them first
var values=[...document.getElementsByTagName("li")].map(el=>el.textContent);
Now you can store this array
localStorage.setItem("todos",values);
If the page is loaded, add it back to the page:
localStorage.getItem("todos").forEach(fumction(value){
//create elem
elem.textContent=value;
});
You could also store a HTML collection, but i wouldnt, storing just the text is.much easier...
Here is a quick example where I store an item and give it a name in localStorage called input. This shows how to setItem() and getItem().
Looks like this example doesn't work in the SO sandbox, so here's a codepen - http://codepen.io/anon/pen/KaNZxX
$('button').on('click',function() {
localStorage.setItem("input", $('input').val());
fetch();
});
function fetch() {
$('#storage').html(localStorage.getItem('input'));
}
fetch(); // fetch on load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"> <button>add</button>
<div id="storage"></div>

JS - How to select and line-through the items in html list by pressing on a button?

I'm just starting to learn JS and collided with a specific task that i dont understand how to solve.
Suppose we have a page that has a list, and there is a button with which I can supplement this list with new cases.
 The problem that I encountered:
 I need to implement a function in a certain way that will change the style of the selected line from the list of all existing and added elements.
 For example, if our list - "a list of things that we have to do", i need to make so that the user can press the "Done" button, and select the desired line. After the selection the selected line gets a line-through.
function addItemToTheList() {
var newItem = document.createElement("li");
var input = document.getElementById("Input");
newItem.innerHTML = input.value;
input.value = "";
document.getElementById("todo").appendChild(newItem);
}
#todo {
font-family: Arial;
}
#todo .done {
color:gray;
text-decoration:line-through;
}
<!doctype html>
<html>
<head>
<title> How can user change added and predefined elements in the list?</title>
</head>
<pre>
<input type = "text" id = "Input" maxlength = "42" size = "42" placeholder = " Add a task here"> <input
type = "button" value = "Add" onclick = "addItemToTheList()">
</pre>
<hr align = "left" width = "378">
<body>
<div id = "todoList">
<ol id = "todo">
<li class = "done"> Watch all seasons of "Game of Thrones"</li>
<li class = "done"> Write a book</li>
<li class = "undone"> Learn "JS"</li>
</ol>
</div>
</body>
</html>
Would anybody be willing to point me in the right direction?
You have to add, first, a click event on each undone tasks.
Then when you create a task just add another clickevent.
Then you just have to click on an undone tasks to change his state.
Hope this is what you want :
function addItemToTheList() {
var newItem = document.createElement("li");
var input = document.getElementById("Input");
newItem.innerHTML = input.value;
input.value = "";
document.getElementById("todo").appendChild(newItem);
// Add click listener
newItem.addEventListener('click', done);
}
function done() {
this.className = "done";
this.removeEventListener('click',done);
}
// Initialize all listener for current undone tasks
function init() {
var undoneItems = document.getElementsByClassName('undone');
for(var i = 0; i < undoneItems.length; i++){
undoneItems[i].addEventListener('click', done);
}
}
#todo {
font-family: Arial;
}
#todo .done {
color:gray;
text-decoration:line-through;
}
#todo .undone {
cursor: pointer;
}
<!doctype html>
<html>
<head>
<title> How can user change added and predefined elements in the list?</title>
</head>
<body onload="init()">
<pre>
<input type = "text" id = "Input" maxlength = "42" size = "42" placeholder = " Add a task here"> <input
type = "button" value = "Add" onclick = "addItemToTheList()">
</pre>
<hr align = "left" width = "378">
<div id = "todoList">
<ol id = "todo">
<li class = "done"> Watch all seasons of "Game of Thrones"</li>
<li class = "done"> Write a book</li>
<li class = "undone"> Learn "JS"</li>
</ol>
</div>
</body>
</html>
You need to create another function, add a button to each of the li items and add an on click function to each button to change the class to done.
Here is a jsfiddle link where i've begun the work required. It isn't fully functional but what would you learn from me doing everything :)
https://jsfiddle.net/nu6b00o0/
(function(){
var buttons = document.getElementsByTagName('button');
for(i = 0; i <= buttons.length -1; i++){
buttons[i].addEventListener('click', function() {
doOrUndoItem();
}, false);
if(buttons[i].parentNode.className == 'done'){
buttons[i].className = 'btn-success';
} else {
buttons[i].className = 'btn-warning';
}
}
}());
Feel free to ask any more questions
Tom
Hope this helps...
//list your pre existing items
var items = document.querySelectorAll("li");
function createListElement(){
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
//add the function in your new items
li.addEventListener("click", alterStatus)
//
input.value = "";
}
// add/remove class
function alterStatus(){
this.classList.toggle("done");
}
//set the function to the pre existing items
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", alterStatus);
}

local storage not giving correct results

i am trying to build post it notes. I am reading Head First Series.
I did this code.
but somehow it's no working.
<form action="post">
<input id="note_text" type="text" placeholder="enter your Note">
<input type="button" id="add_button" value="Add Note">
</form>
<ul id="postItNotesList">
<li>This is my very first note.</li>
<li>This is my very Second note.</li>
</ul>
And here is the Js
window.onload=init;
// Add Sticky to Page
function addStickyToPage(value) {
var sticky = document.createElement("li");
span.setAttribute("class", "sticky");
document.getElementById("postItNotesList").appendChild(sticky);
}
// Create and get Sticky Note into the localStorage
function createSticky() {
var value = document.getElementById("note_text").value;
var key = "sticky_" + localStorage.length;
localStorage.setItem(key, value);
addStickyToPage(value);
}
function init() {
var button = document.getElementById("add_button");
button.onclick = createSticky;
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.substring(0, 6) == "sticky") {
var value = localStorage.getItem(key);
addStickyToPage(value);
}
}
}
So i've buld up a fiddle so that you can easily check it out
Here is the Fiddle
Please tell me where i am doing it wrong.
Thanks.
I have updated your Fiddle. Note : first you should create DOM element and then append text to this element and finally append this node to you body so your code should be like this:
window.onload=init();
function addStickyToPage(value) {
var sticky = document.createElement("li");
sticky.setAttribute("class", "sticky");
var t = document.createTextNode(value);
console.log(t);
sticky.appendChild(t);
document.getElementById("postItNotesList").appendChild(sticky);
}
And also windows.onload = init()with brackets
Thanks

How to delete items and clear a form using javascript

I apologize for posting this question, I'm just learning JavaScript and have tried using the information from other posts but just cannot get my code to work. The object is to create an li tag and insert list items to this newly created tag, then assign an event handler to remove an item if the user clicks on it.
I have the list populating and can remove an item if I hardcode it but cannot for the life of me figure out how to assign the value of the item being clicked on to the removeItem function. I am also trying to clear the list when an item is entered but keep getting the error "Object doesn't support property or method 'reset'".
If someone could point me in the right direction I would appreciate it.
thanks!
<!doctype html>
<html lang="en">
<head>
<title> Add and delete items Objective </title>
<meta charset="utf-8">
<style>
p {
font-style: italic;
}
li:hover {
cursor: pointer;
}
</style>
<script>
// your code here!
var itemList = [];
window.onload = init;
function init() {
var addButton = document.getElementById("submitButton");
addButton.onclick = addItem;
//var itemList = document.getElementById("list");
var itemsList = document.getElementsByTagName("li");
itemsList.onclick = removeItem;
}
function addItem() {
var newItem = document.getElementById("item").value;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(newItem));
ul.appendChild(li);
itemList.push(newItem);
document.getElementById("item").reset();
}
function removeItem() {
var editList = document.getElementsByTagName("li");
// var editList = document.getElementsById("list");
for (var i = 0; i < editList.length; i++) {
var item = editList[i];
if(editList.options[i].selected) {
editList.removeChild(editList.childNodes[i]);
}
}
}
</script>
</head>
<body>
<form>
<label form="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="list">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
</html>
Why not set the value of the item input to an empty string rather than using reset?
document.getElementById("item").value = "";
As for removing the list items...
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].addEventListener("click", removeItem);
}
you can only reset forms, so you have to select the form and then reset will work. f.e. with:
document.forms[0].reset()
your code is adding the eventhandler to all existing li-Elements, if you create some new li-Elements later, you have to add the eventhandler to it manually. f.e. in your addItem-Function with:
li.onclick = removeItem;
after pushing the new Item
in your removeItem-Function you have access on the clicked Element via this, so you can remove only this Element with:
this.remove()
You could change your addItem() and removeItem() functions :
function addItem() {
var newItem = document.getElementById("item").value;
$('#list').append("<li id='" + newItem + "' onclick='removeItem(this)'>" + newItem + "</li>");
}
function removeItem(id) {
$(id).remove();
}

localstorage how to save a button

I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>

Categories

Resources