So I'm trying to start on a to do list in html5 + jQuery using Local Storage, but for some odd reason I can't get the jQuery to make a local storage key.
Here is my code. I want it to collect the value of the input box, add it to local storage, and then print the code in the div named.
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = this.localStorage.setItem('task_',input_value);
var task = this.localStorage.getItem('task_');
$('#taskList').append("<br>"+task);
};
return false;
});
and then the HTML...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="shit.js"></script>
</head>
<div id="cNew">
<form id="taskEntryForm">
<input id="taskInput" name="taskInput" autofocus></form>
</div>
<div id="taskList"></div>
</html>
In your code this stands for form. Local storage object is not part of the form, it is a part of window. You should change this (which represents form) to window, or remove this at all (because window.localStorage is identical to just localStorage):
$('#taskEntryForm').submit(function () {
if ($('#taskInput').val() !== '') {
var input_value = $('#taskInput').val();
var stored_input = localStorage.setItem('task_',input_value); // <- removed 'this'
var task = localStorage.getItem('task_'); // <- removed 'this'
$('#taskList').append("<br>"+task);
};
return false;
});
Here is a working jsFiddle
Related
I am trying to retain data in a localstorage after reload but it is not working
this is my attempt
<script>
window.onbeforeunload = function() {
localStorage.setItem(name, $('#inputName').val());
}
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) $('#inputName').val(name);
alert(name);
}
</script>
<html>
<body>
<input type="text" id="inputName" placeholder="Name" required>
</body>
</html>
on refreshing the page after entering data on the form it keeps alerting null. kindly assist
In your onbeforeunload, name is the name of the window (because you haven't given it any other value, and browsers have a global name property which is the name of the window — it's usually blank).
In this line:
var name = localStorage.getItem(name);
...it's undefined, because of the var name.
You need to use a proper name, for instance:
window.onbeforeunload = function() {
localStorage.setItem("your-setting-name", $('#inputName').val());
};
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) $('#inputName').val(name);
alert(name);
};
Also note charlietfl's oint that if you don't want to alert null on the first visit to the page, you need to put the alert in the body of the if:
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) {
$('#inputName').val(name);
alert(name);
}
};
Otherwise, it'll alert null on the first visit and then whatever the last value was otherwise.
(Also note that I've added some missing ;. Automatic Semicolon Insertion will add these particular ones, but it's an error-correction mechanism, so I'd advise not relying on it.)
Other issues:
You're using jQuery functions, but haven't shown any script tag including jQuery on the page.
You have the closing </html> tag before the <input ...> tag.
Here's a fiddle with the above fixed (can't use Stack Snippets with local storage): https://jsfiddle.net/un86not0/ Full working page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Example</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
window.onbeforeunload = function() {
localStorage.setItem("your-setting-name", $('#inputName').val());
};
window.onload = function() {
var name = localStorage.getItem("your-setting-name");
if (name !== null) {
$('#inputName').val(name);
alert(name);
}
};
</script>
<input type="text" id="inputName" placeholder="Name" required>
</body>
</html>
The variable name haven't been initiated yet you already used it as a value reference. Maybe it wasn't working well because of that?
Here in this solution, you can separately reference the local storage item without using the variable name which might have caused it not to work.
<script>
window.onbeforeunload = function() {
localStorage.setItem('myItem', $('#inputName').val());
}
window.onload = function() {
var name = localStorage.getItem('myItem');
if (name !== null) $('#inputName').val(name);
alert(name);
}
</script>
I made a button click counter for a website using some JavaScript.
The counter works well, but now I'm stuck in making the saving of the count. You know, if I click the button 3 times, the text says 3 Times. But I want to save that value so if the user refreshes the page, it should display 3 Times again.
I knew of using localStorage, I followed a simple tutorial and applied it to my code, but it does not seem to be working. When I run the page in Microsoft Edge and see the Debug page (F12), the console throws an error that says: Unable to get property 'getItem' of undefined or null reference. I searched in other posts but no one of these could solve my problem. It seems to be stuck when retrieving the value in localStorage.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Registrar" id="countButton" />
<input id="ocityField" type="text" value="" placeholder="Ciudad de Origen"/>
<input id="cityField" type="text" value="" placeholder="Ciudad de participación"/>
<input id="name" type="text" value="" placeholder="Nombre"/>
<p>Personas Registradas: <span id="displayCount">0</span></p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var textbox = document.getElementById("ocityField");
var textboxa = document.getElementById("cityField");
var textboxb = document.getElementById("name");
if(window.localStorage.getItem('count')){
var savedcount = window.localStorage.getItem('count');
count = window.localStorage.getItem('count');
}else{
count = 0;
}
display.innerHTML = count;
button.onclick = function(){
var mystring = textbox.value;
var mystring2 = textboxa.value;
var mystring3 = textboxb.value;
if(!mystring.match(/\S/) || !mystring2.match(/\S/) || !mystring3.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
count++;
window.localStorage.setItem('count', count);
display.innerHTML = count;
textbox.value = "";
textboxa.value = "";
textboxb.value = "";
return true;
}
}
</script>
</body>
</html>
I tried using window.localStorage and just localStorage but no one did work.
May be that you use the IE browser does not support localStorage,The code can run in Chrome49.
Can I Use localStorage, here you can check what browser supports localStorage with version numbers.
Alternate way to store data on client side is cookies if localStorage doesn't supported by browser.
You can also use third party plugins like Modernizer, to check whether browser supports or not.
Modernizr.localstorage if it evaluate to true the browser supports localStorage.
Following example demonstrates localStorage and cookies depending on browser compatibility. uses Modernizer and jQuery
codepen
I have a Raspberry PI with a button attached to it.
I run a Python script on it to detect when the button is pressed.
When the button is pressed, it increment a number in a text file.
I need to display this number on a web page (Apache) and to launch a sound.
For the moment, my python script change the index.html with the value I need and I am using <meta http-equiv="refresh" content="1"> to resfresh the page.
The problem is that I need to know when the number is changing to launch the sound.
Too little information to say something concrete, but here's how I'd get around to it given the main following limitation that the page is not dynamic (no ajax).
General outline:
Put the value from the text file in a identifiable field like
<span id="myNumber">#the number from file goes here </span>
then on load with java script read the value of the field:
(planin JS)
var myNumberValue = document.getElementById('myNumber').innerHTML;
then create a cookie to store the last value on clinets machine:
document.cookie = "lastNumber="+myNumberValue;
To sum it all up: on loading the webpage launch a script that will :
check for a cookie
read a value from the coookie
(http://www.w3schools.com/js/js_cookies.asp)
read a value from the field
if a cookie exists compare the values and if the number
changed play a sound like here:
Playing audio with Javascript?
either way store the value from the field to the cookie for next
website update.
[Edit] Full working solution using local storage or cookies:
<html>
<head>
<META HTTP-EQUIV="refresh" CONTENT="5">
<script type="text/JavaScript">
function myFunction()
{
var numberDisplayed = parseInt(document.getElementById('myNumber').innerHTML);
var numberInCookie = numberDisplayed;
//lets assume that's the only data in the cookie
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(numberDisplayed!=numberInCookie)
{
alert("changed to from "+ numberInCookie+" to " + numberDisplayed);
}
saveNumber(numberDisplayed);
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that's the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>
[Edit 2] as the author of the question hinted he doesn't actually want to use the site refresh here's another option:
lest start a loop that will load a test file from the server as an ajax request. then the data is loaded, parsed, store it loacally as before. and set timer to trigger the refresh again.
One importatnt thing the files need to be available on the same domain / server (see HTTP access control (CORS) for more information)
<html>
<head>
<script type="text/JavaScript">
var externalNumber = 0;
var timer;
function myFunction()
{
// start the readouts:
LoadExternalData();
}
function LoadExternalData()
{
var client = new XMLHttpRequest();
client.open("GET", "http:/myserver/readme.txt");
client.onreadystatechange = function() {
externalNumber = parseInt(responseText);
//store a local copy
var NewestNumber = externalNumber;
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(NewestNumber!=numberInCookie)
{
alert("changed to from current "+ numberInCookie+" to " + NewestNumber);
}
saveNumber(NewestNumber);
timer = setTimeout(LoadExternalData, 1000);
}
client.send();
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that is the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>
So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();
Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});