I am unable to use local storage for javascript. This is my first time trying local storage. I have two seperate HTML docs each with their own set of javascript code.
Doc 1 Javascript:
<script>
function callData() {
document.getElementById("1").innerHTML = localStorage.getItem("name1");
document.getElementById("2").innerHTML = localStorage.getItem("name2");
document.getElementById("3").innerHTML = localStorage.getItem("name3");
setNames();
}
function setNames() {
var 1st = document.getElementById("1").innerHTML;
var 2nd = document.getElementById("2").innerHTML;
var 3rd = document.getElementById("3").innerHTML;
if (typeof(Storage) != "undefined") {
localStorage.setItem("1", 1st);
localStorage.setItem("2", 2nd);
localStorage.setItem("3", 3rd);
}
else {
alert("Sorry, your browser does not support Web Storage"); }
}
</script>
Doc 1 Html
<body onLoad = "callData()">
<a style="text-align:left;" href= cameraApp.html>New Contact</a>
<h1 style="background-color:black; color:white; font-family:helvettica;">Address Book</h1>
<h3 style="background-color:blue; color:white; font-family:helvettica;">Contacts</h3>
<a id=1></a>
<a id=2></a>
<a id=3></a>
</body
Doc 2 JavaScript
<script>
function done() {
var 1st = localStorage.getItem("1");
var 2nd = localStorage.getItem("2");
var 3rd = localStorage.getItem("3");
var name = document.getElementById('nameTextfield').value;
if(1st = "") {
localStorage.setItem("name1",name);
alert("Success, Contact created");
} else if(2nd = "") {
localStorage.setItem("name2",name);
alert("Success, Contact created");
} else if(3rd = "") {
localStorage.setItem("name3",name);
alert("Success, Contact created");
} else {
alert("Sorry, Maximum contact limit reached");
}
}
</script>
</head>
Doc 2 HTML
<body>
<a style="text-align:left;" href= phonebook.html>Back</a>
<h1 style="background-color:black; color:white; font-family:helvettica;">Create a Contact</h1><br>
<form name="info">
<p id="name">Name: </p><input id="nameTextfield" type="textfield"/><br>
</form>
<button onclick="done()">Done</button>
</form>
</body>
The Doc 2 is meant to store the name given by the user and pass it to the Local Storage. Doc 1 is then supposed to display the names that have been stored in the local storage. Whenever I try to use this, after clicking the done button on doc 2 the page just refreshes and when I go back to doc 1 no names are added. I am using the Android SDK for the coding. I have tried using local storage for a hello world document so I know that it works for SDK.
Variable names can't start with numbers (Correct me if i'm wrong).
Which is throwing error
Uncaught SyntaxError: Unexpected token ILLEGAL.
Also, you're checking whether the value exists or not by comparing to empty string (""), which will not also work,
You can check it instead like
if(!variable){
//variable does not exist
}
fixing these seems to solve the issue
Doc1
Doc2
Related
I am trying to create a URL shortener using jsonbase.com and vanilla javascript.
button tag in HTML was not able to recognize the method "shortUrl" from my js file. So, I directly added the code of add event listener in the js file.
index.html
<body>
<div id="app">
<input type="url" id="urlinput">
<input id="mybutton" type="button" value="Short the URL"/>
</input>
</div>
<script src="src/index.js"></script>
</body>
Now, I am getting an error - Javascript type error - The "listener" argument must be of type Function. Received type object - when I am trying to use jsonbase.com for storing the data.
script.js
function shortUrl() {
var longurl = getURL();
genHash();
var uniqueHash = window.location.hash.substr(1);
sendRequest(longurl, uniqueHash);
if (window.location.hash !== "") {
var short = getRequest(uniqueHash);
if (short !== "") {
window.location.herf = "short";
}
}
}
use of jsonbase.com
var jsonbase = require("jsonbase.com");
var token = "mytoken";
var store = jsonbase(token);
var endpoint = `jsonbase.com/${token}`;
//sending request
function sendRequest(longURL, uniqueHash) {
store.write(`${endpoint}/${uniqueHash}`, longURL);
}
//getting request
function getRequest(uniqueHash) {
return store.read(`${endpoint}/${uniqueHash}`).then((response) => {
return response.data;
});
}
generating hash for shorter
function genHash() {
if (window.location.hash === "") {
window.location.hash = getRandomStr();
}
}
Error screenshot -
I have created a reproducible sample code sandbox for my private application - https://codesandbox.io/s/url-shortner-t3ov2
Please let me know if any more info is required.
The issue is not your code, the issue is the package not parsing the JSON correctly, try using a different package
I know this does not answer your question, but it should solve it
i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);
Hello , This is the code that can change the image src and I am using it offline .It has 2 button , one of which turns on the light and other turns off it. It works well! But problem is it doesn't remember the choice i made once i reload the page. Ex. If i turn on the light , it shows the glowing bulb but forgets after reload.
Note: I have tried some online solutions but since it was about something related to javascript, it didn't seem to work.
Target is chrome only!
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.
</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off
the light</button>
</body>
</html>
As already noted you can use localStorage to store the src and load it next page load. To use this for your example you could use the following code:-
Html
<button id="btn1">Turn on the light</button>
<img id="myImage" src="off.png">
<button id="btn2">Turn off the light</button>
JS
//set src on page load
if(localStorage.imgSrc) {
document.getElementById('myImage').src = localStorage.imgSrc;
}
//set src and localStorage on click
document.getElementById('btn1').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'on.png';
}
document.getElementById('btn2').onclick = function() {
localStorage.imgSrc = document.getElementById('myImage').src = 'off.png';
}
You can use either localstorage that is being supported by the most modern browsers or use cookie.
What i would do is to check in a function if localstorage is being supported if not use cookie like this
function localStorageExists(){
try {
localStorage.setItem(simpleTest, simpleTest);
localStorage.removeItem(simpleTest);
return true;
} catch(e) {
return false;
}
}
function saveOption(value) {
if(localStorageExists() === true){
// available use local storage
localStorage.setItem(option, value);
}else{
// unavailable use cookie
createCookie("option", value, 30);
}
}
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
you can also have a function that detects and reads accordingly ;)
I'm trying to save a cookie and then load it again
I have this code
<html>
<head>
<script>
var myCookies = {};
function saveCookies()
{
myCookies["_uuser"] = document.getElementById("user").value;
myCookies["_uuage"] = document.getElementById("age").value;
//Start Reuseable Section
document.cookie = "";
var expiresAttrib = new Date(Date.now()+60*1000).toString();
var cookieString = "";
for (var key in myCookies)
{
cookieString = key+"="+myCookies[key]+";"+expiresAttrib+";";
document.cookie = cookieString;
}
//End Reuseable Section
document.getElementById("out").innerHTML = document.cookie;
}
function loadCookies()
{
//Start Reuseable Section
myCookies = {};
var kv = document.cookie.split(";");
for (var id in kv)
{
var cookie = kv[id].split("=");
myCookies[cookie[0].trim()] = cookie[1];
}
//End Reuseable Section
document.getElementById("user").value = myCookies["_uuser"];
document.getElementById("age").value = myCookies["_uuage"];
}
</script>
</head>
<body>
User: <input type="text" id="user">
Age: <input type="text" id="age">
<button onclick="saveCookies()">Save To Cookies</button>
<button onclick="loadCookies()">Load From Cookies</button>
<p id="out"></p>
</body>
</html>
when I type an input for both name and age, and click on save to cookies,
and then clock on load from cookies, I got this "undefined" for both user and age!!
what's missing in my code, so I can save the cookie
For Chrome cookies can only be set, when the page is running on a webserver.
For example accessed via http://localhost/foo/bar.html or http://127.0.0.1/foo/bar.html
edit: you might check out as well this answer:
where cookie saved for local HTML file
I just tested it myself: it works with Firefox.
Otherwise it would be better for testing such cases, to put up a local webserver like apache
I have tested your code from a web server and it works fine.
You must load it from a web server, rather from the local file system.
JSFiddle is here if you want to prove it for yourself.
https://jsfiddle.net/brx5ropp/
Note that due to JSFiddle limitations I had to move the click triggers for the buttons to code like this:
document.getElementById("load").addEventListener("click", loadCookies);
document.getElementById("save").addEventListener("click", saveCookies);
...but that is irrelevant to my answer!
So I am having a problem with HTML5 and javascript.
I made a few .js files for the javascript part and I made the link to connect it with the HMTL code but it will not show the javascript part.
This is my HTML
<!doctype html>
<html lang="en">
<head>
<title>Gateway Tunes</title>
<meta charset="utf-8" />
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
and here are my javascript files; the names of the files are at the top
playlist_store.js
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify (playlistArray));
}
function loadPlaylist() {
var playlistArray = getSavedSongs();
var ul = document.getElementById('playlist");
if (playlistArray !Null) {
for (var i = 0; i < playlistArray.length; i++) {
li.innerHTML = playlistArrray[i];
ul.appenChild(li);
}
}
}
function getSavedSongs() {
return getStoreArray("playlist")
}
function getStoreArray (key);
var playlistArray = localStorage.getItem(key);
if(playlistArray == null || playlistArray == "") {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse (playlistArray);
}
return playlistArray;
}
playlist.js
window.onload = init;
function init() {
var button = document.getElementById ("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick () {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Button was clicked!");
}
else {
alert("Your track has been added!");
}
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
}
You've got some syntax errors so your javascript isn't running.
In playlist_store.js
var ul = document.getElementById('playlist");
Opens a string with ' but tries to close it with ". It doesn't matter which you use as long as you're consistent, so you can either change it to 'playlist' or "playlist".
if (playlistArray !Null) {
If you're trying to make sure playlistArray isn't null you can do
if (playlistArray != null) {
notice != as the comparison and null needs to be lowercase. If you want to make sure it isn't just undefined or null you can simply do if (!playlistArray).
ul.appenChild(li); needs to be ul.appendChild(li);.
I'm sure there's more, check over your code.
The first line of your script (and the only one that isn't just a function definition) is window.onload = init;. This means that after the page has loaded, your init function is called.
This function looks up the element with id addbutton, and then calls a method on the returned result. Since you don't have an element with this ID, there won't be any object returned, and so an exception will be thrown (something like "button is null or not an object", depending on your browser). This exception stops the method from executing further - and in particular, loadPlaylist() will not be called.
The moral of the story here though is pay attention to the JavaScript error console, especially while you're doing development! You browser will almost certainly have displayed a red exclamation mark icon or similar, which you could double-click to give you the name, message and location of the exception.
You really don't need to post your code listing on Stack Overflow to ask us what's wrong with it, when your browser is already capable of telling you exactly where the problem is.