localstorage how to save a button - javascript

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>

Related

Multiple Buttons to insert text into input

I am attempting to have a button with a search value for our most common searches. What I was trying to do is user clicks button and inserts the text WITH the quotes "Some Text".
Right now this is what I am using for a single button. How would I make this so I can use one script with multiple buttons?
<button onclick="searchText()" data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button> <----Current Button
<button onclick="searchText()" data-product-name="Pixel 5">Pixel</button> <---- Added for what Id like
<button onclick="searchText()" data-product-name="LG">LG</button><---- Added for what Id like
<button onclick="searchText()" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like
<script>
var i = 0;
var txt = '"iPhone 12 Pro Max"';
var speed = 50;
function searchText() {
if (i < txt.length) {
document.getElementById("search-query").value += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
I tried adding the following but did not work.
var txt = element.getAttribute('data-product-name');
var i = 0;
var txt = '"iPhone 12 Pro Max"';
var speed = 50;
var elements = document.querySelectorAll('button')
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
var txt = this.getAttribute('data-product-name');
console.log(txt);
});
}
<button data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button>
<button data-product-name="Pixel 5">Pixel</button>
<button data-product-name="LG">LG</button>
<button data-product-name="Samsung S20 Plus">Samsung S20 Plus</button>
You can pass the id of the button to the searchText.
and read the text using jquery or plain js
<!--html --->
<button onclick="searchText('buttonOne')" id= "buttonOne" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like
// javascript
function(buttonId){
var text = document.getElementById(buttonId).innerHTML
// process the text with your business logic here
}

How to add user prompt input to an array permenantly

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>

"reuse" a JavaScript code for multiple buttons

I am fairly new to JavaScript,
I have ben working on a simple if else script to change the color of at button, depending on the status of a variable that I get from a plc (Siemens S7-1200).
The script is working fine and the color of the button is changing.
But I have 10 buttons that I want to run this script on.
Is it possible to “reuse” the script so that I don’t have to copy the script and change the variables for every button
T
<script>
var tag = ':="web_DB".outtag1:'
var button = "button1"
window.onload = function() {
if (tag == 1) {
document.getElementById(button).style.backgroundColor = 'green';
} else{
document.getElementById(button).style.backgroundColor = 'red';
}
}
</script>
<form>
<input type="submit" id="button1" value="button">
<input type="hidden" name='"web_DB".intag1' value ="1">
</form>
It's hard to be sure since you haven't posted all your code and what you have posted doesn't actually work but I think you're looking for something like this.
const tags = [
':="web_DB".outtag1:',
':="web_DB".outtag2:',
//...
':="web_DB".outtag10:'
];
window.onload = function() {
for (let i = 0; i <= 9; i++) {
const color = (tags[i] == 1) ? 'green' : 'red';
document.getElementById('button' + (i+1)).style.backgroundColor = color;
}
}

Remove checked checkboxes

I am making a To-do list, where I want to be able to add new tasks, and delete tasks that are checked off. However, it seems my function just deletes all tasks, not just the ones that are checked off. Neither does it seem to allow new tasks to be added.
html:
<h1 id="title"> To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin"></input>
<button id="add">add</button>
javascript:
<button id="clear">Clear completed tasks</button>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function() {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
})
clear.addEventListener("click", function() {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
task_area.remove(tasks.children[i])
}
}
})
jsfiddle: https://jsfiddle.net/4coxL3um/
.remove removes the element you are calling it from, and doesn't take an argument for what to remove. The following:
task_area.remove(tasks.children[i])
should be
tasks.children[i].remove()
EDIT: As Mononess commented below, this will only remove the checkboxes and not the labels. While you could delete both using Jayesh Goyani's answer below, it's probably better that each input/label pair be wrapped in a single div or span for easier management.
You could try adding an event listener to each child of task_area that calls the below function. Haven't gotten a chance to test it out, and may not fulfill all of your requirements, but should get the job done.
function removeClicked() {
this.parentNode.removeChild(this);
}
Please try with the below code snippet. Below code will help you to remove selected checkbox with label.
<body>
<h1 id="title">To-do list</h1>
<div id="task_area">
</div>
<input type="text" id="putin" />
<button id="add">add</button>
<button id="clear">Clear completed tasks</button>
<script>
var tasks = document.getElementById("task_area")
var new_task = document.getElementById("add")
var clear = document.getElementById("clear")
new_task.addEventListener("click", function () {
var putin = document.getElementById("putin")
var input = document.createElement('input')
input.type = "checkbox"
var label = document.createElement('label')
label.appendChild(document.createTextNode(putin.value))
task_area.appendChild(input)
task_area.appendChild(label)
//document.getElementById("task_area").innerHTML = putin.value
})
clear.addEventListener("click", function () {
for (i = 0; i < task_area.children.length; i++) {
if (task_area.children[i].checked === true) {
tasks.children[i].nextSibling.remove();
tasks.children[i].remove();
}
}
})
</script>
</body>
Please let me know if any concern.

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

Categories

Resources