how to save a button - javascript

I want to save this button so that when i close the browser and reopen it i still is white.
I tried a lot but i just don't get the solution.
<script>
function save(){
var storeButton = document.getElementById("testButton1");
localStorage.setItem("button", storeButton)
}
function load(){
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementById("testButton1") = storedButton;
}
}
</script>
<body onload="load()">
<input class="blue" type="button" id="testButton1" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
<input type="button" id="testButton" value="Save" onclick="save()"/>
</body>

You cannot save the button itself since local storage only stores strings.
Instead, save the information that you need in the form of a string (in this case, the color):
function save() {
var storeButton = document.getElementById("testButton1");
localStorage.setItem("buttonColor", storeButton.style.backgroundColor);
}
function load() {
var color = localStorage.getItem("buttonColor");
if (color) {
document.getElementById("testButton1").style.backgroundColor = color;
}
}

Related

Local storage example doesn't work how I expect it to be

In my Web university course there is this example with local storage and it says it should show in the input area the number of clicks on the button and also store it in localstorage, but all I get is NaN on the input no matter how many times I click on the button.
<head>
<script>
window.onload = function()
{
var el=document.getElementById("bt");
el.onclick= function()
{
var x = parseInt(localStorage.getItem("nrc"));
if (x!==NaN){
localStorage.setItem("nrc", x + 1);
}
else{
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
var buton2=document.getElementById("bt2");
buton2.onlick = function ()
{
localStorage.removeItem("nrc");
}
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
<button id="bt2"> Click2</button>
</body>
Edit: problem was solved, but now if i want to remove an item from local storage or clear the localstorage it doesn't work.
You have a typo, you wrote onlick instead of onclick
buton2.onclick = function() {
console.log('clearing storage!');
localStorage.removeItem("nrc");
// Reset input back to zero
document.getElementById("write").value = '0';
}
Complete working example here
You were checking a non number to a non number which will always true.
Anyways the solution is already posted in the comments
<head>
<script>
window.onload = function() {
var el = document.getElementById("bt");
el.onclick = function() {
var x = parseInt(localStorage.getItem("nrc"));
if (!isNaN(x)) {
localStorage.setItem("nrc", x + 1);
} else {
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
</body>

Trying to save all generated 'li' elements to local storage using JavaScript

This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//CanĀ“t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working

jQuery onclick method doesn't work twice

I have 2 onclick methods. The first one works fine but the second one doesn't works if i click first one, I need to refresh the page to run. Even if I do that, it only works once.
$(document).ready(function(){
$(".cart_add").on('click','.add_cart',function(){
var product_id = $(this).data("productid");
var size = $('ul#size').find('li.active a').data('value');
var qty = $('.qty-input').val();
var price = $('.special-price').data('price');
var name = $('h1.product-name').text();
var url = $(this).data("url");
$.post(url,{product_id:product_id,product_size:size,product_name:name,product_price:price,product_qty:qty},function(response){
$(".variant-1").html(response);
});
});
$(".secondary").on('click','.delete',function(){
var product_id = $(this).data("id");
var url = $(this).data("url");
$.post(url,{product_id:product_id},function(response){
$(".variant-1").html(response);
});
});
})
$("#CheckClick").click(function(){
alert("The paragraph was clicked.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-success" id="CheckClick">button</button>
Take ID Instead of Class check in side your code
or take your script inside function and call it on button click
function myFunction(){
alert("it's work well")
}
<input id="clickMe" type="button" value="clickme" onclick="myFunction();" />
you can try using onclick event from html button like`
function myFunction() {
alert('"hello"');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="myFunction()">Click me</button>
e`

Save data to localstorage, display it by innerHTML ,if there is nothing in the data,show the original text of span(Visitors)

I've made this code for saving a form data to localstorage
<HTML>
<head>
<script>
function myfunction1() { texttosave = document.getElementById('textline').value; localStorage.setItem('mynumber', texttosave); } function myfunction2() { document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } function myfunction3() { localStorage.removeItem('mynumber'); return ''; }
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name" /> <button id="rememberer"
onclick='myfunction1()'>Save</button> <button id="recaller" onclick='myfunction3()'>Delete Your Name</button>
<br>
Welcome<span id="recalledtext">Dear Visitor,</span> Refresh the page to see changes
</body>
</HTML>
If you enter your name and click the save button,it saves your name into localstorage. Then if you Refresh the page,You will see "Welcome 'Your Name' Refresh the page to see changes" below the form.You can simply delete your name from localstorage by clicking the delete button.
All that tasks are working. But if the visitor didn't saved any name or if the visitor click over the delete button, I want to show the original text which is inside the span(Dear Visitor,). Please tell me how to do that
You can make a new myfunction4() which resets the value (although perhaps you can find a better name for it than that):
function myfunction4(){
document.getElementById('recalledtext').innerHTML = "Dear visitor,";
}
And you can call it when the user clicks delete:
function myfunction3() {
localStorage.removeItem('mynumber');
myfunction4();
return '';
}
When the name saved is blank, you don't really need to do anything at all.
function myfunction2() {
if(localStorage.getItem('mynumber')!="") {
document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber');
}
}
I have changed the code into this:
<HTML>
<head>
<script>
function myfunction1(){texttosave = document.getElementById('textline').value ; localStorage.setItem('mynumber', texttosave); } function myfunction2() { if(localStorage.getItem('mynumber')!="") { document.getElementById('recalledtext').innerHTML = localStorage.getItem('mynumber'); } } function myfunction4(){ document.getElementById('recalledtext').innerHTML = "Dear visitor"; } function myfunction5(){texttosav = document.getElementById('Default').value ; localStorage.setItem('mynumber', texttosav); } function myfunction6(){ textdata = document.getElementById('textline').value ; document.getElementById('recalledtext').innerHTML = textdata; }
</script>
</head>
<body onload='myfunction2()'>
<input type="text" id="textline" placeholder="Enter Your Name"/>
<input type="hidden" id="Default"value="Dear Visitor" placeholder="Enter Your Name"/><button id="rememberer" onclick='myfunction1();myfunction6();'>remember text</button> <button id="recaller" onclick='myfunction4();myfunction5();'>Delete Your Name</button>
<br>
Welcome <span id="recalledtext" >Dear Visitor</span>, Refresh the page to see changes
</body>
</HTML>
And now it's perfectly working.

How can I save a number into a javascript cookie that can be printed on the screen

I want to have a button which when you click on it adds 1 to a number, which is displayed on the screen. This is how far I got.
<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>
<script>
function addOne()
{
i++;
document.getElementById('inc').value = i;
}
</script>
How can I make it so that the number is saved into a cookie so whenever I come back the number is not changed back into 0?
The variable i has no starting value. You could do the following:
updated, see http://jsfiddle.net/sUHy2/4/
<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>
<button onclick="resetCookie()">Reset Cookie</button>
<script>
function resetCookie()
{
document.cookie = 0;
writeValue();
}
function addOne()
{
document.cookie++;
writeValue();
}
function writeValue()
{
document.getElementById('inc').value = document.cookie;
}
window.onload = function(){
if(!document.cookie)
{
document.cookie = 0;
}
writeValue();
}
</script>

Categories