How to set a default value based on user's previous value - javascript

I want to have a default value based on what the user put before. For example, if in an input I put '5' I want to see that the value of that input is 5 when I refresh the page, but if I put 6 I want the default value to be 6. Thanks (i'm a begginer)

Use local storage:
localStorage = window.localStorage;
localStorage.setItem('inputDefault', '5');
let inputDefault = localStorage.getItem('inputDefault');
Here's a more practical example I quickly whipped up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Local Storage Example</title>
<script type="text/javascript">
function setLocalStorageValue()
{
let myNumberInputField = document.getElementById('myNumberInput');
let myNewValue = myNumberInputField.value;
let localStorage = window.localStorage;
localStorage.setItem('defaultValue', myNewValue);
}
function getLocalStoredValue()
{
let localStorage = window.localStorage;
let defaultValue = localStorage.getItem('defaultValue');
let myNumberInputField = document.getElementById('myNumberInput');
myNumberInputField.value = defaultValue;
}
</script>
</head>
<body onload="getLocalStoredValue()">
<label>My Number Input
<input type="number" id="myNumberInput" value="0" onchange="setLocalStorageValue()">
</label>
</body>
</html>
Does this answer your question? Note how I am writing back to local storage on the onchange event of the input in question, and I read from local storage when the body of the html loads.

Related

How to change an Id on another page as it loads through JavaScript

I want for the user to click a button which leads to another page. Depending on what button the user clicks, the page content should look different despite being on the same page. A simplified example is below:
Starting page html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Click Here
Click Here
<script src="script.js"></script>
</body>
</html>
second-page.html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="content-id">*CONTENT SHOULD BE LOADED HERE BASED OFF BUTTON CLICKED*</p>
<script src="script.js"></script>
</body>
</html>
script.js code:
function changeContent(n) {
document.getElementById("content-id").innerHTML = n;
}
The above code does not work. I'm guessing the browser doesn't see the content-id on the first page and fails to change anything before loading the second page. Any way to reference the right id on the right page using JavaScript (no jQuery) when the new page is loaded?
Short answer: there are several approaches, the easier that comes to mind is to use localStorage if you're dealing with same origin pages
What you need is to have user information available across multiple pages. So, unlike sessionStorage, localStorage allows to store data and save it across browser sessions:
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.
To use it, consider adapting your javascript of first page:
function changeContent(n) {
localStorage.setItem('optionChosen', n);
}
Then retrieve it in the second page's javascript.
var opt = localStorage.getItem('optionChosen')
var content = document.querySelector('#content-id')
if (opt == null) console.log("Option null")
if (opt === 'Option One') content.innerText = "Foo"
if (opt === 'Option Two') content.innerText = "Bar"
Edited -
Added 3 working examples that can be copy and pasted.
Problem -
Display content on a new view based on the button clicked to get to that view.
Approach -
You can store the value of ID in the browser to help identify the content that should be displayed in many ways. I will show you three working examples.
Notes -
I am over complicating this a little to show you how you might make this work since I do not know the exact circumstances you are working with. You should be able to use this logic to refactor for your requirements. You will find the following 3 solutions below.
1. Using GET Params
Uses the GET params in the URL to help you track necessary changes in your view.
2. Using Session Storage
A page session lasts as long as the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Closing a tab/window ends the session and clears objects in sessionStorage.
3. Using Local Storage
The difference between localStorage and sessionStorage is the time the data persists. LocalStorage spans multiple windows and lasts beyond the current session.
The memory capacity may change by browser.
Similar to cookies, localStorage is not permanent. The data stored within it is specific to the user and their browser.
Solutions -
Working Examples - (Copy and paste any of the below solutions into an HTML file and they will work in your browser.)
Using GET Params
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
let currentURL = window.location.href.split("?")[0];
function appendParams(val) {
if (val === "a") {
window.location.assign(currentURL + "?id=a");
}
if (val === "b") {
window.location.assign(currentURL + "?id=b");
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="appendParams('a')">Click Here</button>
<button onclick="appendParams('b')">Click Here</button>
<p id="replace-id"></p>
</body>
</html>
<script type="text/javascript">
let url_str = window.location.href;
let url = new URL(url_str);
let search_params = url.searchParams;
let id = search_params.get("id");
document.getElementById("replace-id").id = id;
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("a").innerHTML = ContentOne;
}
if (id === "b") {
document.getElementById("b").innerHTML = ContentTwo;
}
</script>
Using Session Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
sessionStorage.setItem("id", "default");
function addSessionStorage(val) {
sessionStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = sessionStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addSessionStorage('a')">Click Here</button>
<button onclick="addSessionStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>
Using Local Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
localStorage.setItem("id", "default");
function addLocalStorage(val) {
localStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = localStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addLocalStorage('a')">Click Here</button>
<button onclick="addLocalStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>

Trying to make a notepad like script in HTML/JS

Edit: Just confirming: I want what the user typed to be saved so that when he reloads/leaves the webpage and comes back what he wrote earlier is still there.
I tried using cookies but it only put one line of Default(variable) when I reloaded the page. Im trying to get it to work with localStorage now but it sets the textarea to "[object HTMLTextAreaElement]" or blank when I reload. I read that this error can be caused by forgetting to add the .value after getElementById() but I did not make this mistake. I am hosting and testing the webpage on Github(pages). What am I doing wrong? here is the code(ignore the comments also it might not work in jsfiddle bc it localstorage didn't work there for me):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>le epic web page</title>
</head>
<body><!--
= "\n"-->
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
<script>
var Default="P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if(localStorage.getItem("P") == ""){
document.getElementById("txt").value=Default;
localStorage.setItem("P")=Default;
}else{
document.getElementById("txt").value=localStorage.getItem("P");
}
//update cookie (called when typed)
function save(){
var txt=document.getElementById("txt").value;
//txt=txt.replace(/\r\n|\r|\n/g,"</br>");
localStorage.setItem("P",txt);//set cookie to innerHTML of textArea, expires in 1 day
}
//when page closed/reloaded
window.onbeforeunload = function(){
localStorage.setItem("P",txt);//update cookie when page is closed https://stackoverflow.com/a/13443562
}
</script>
</body>
</html>
When you are exiting the page, you are referencing the text element and storing that in localstorage. Since localStorage is a string it converts the html element reference into the text you see.
window.onbeforeunload = function(){
localStorage.setItem("P",txt);
}
You are doing it correctly with save, so just call save with the beforeunload event
window.addEventListener('beforeunload', save);
Another bug in the code is the line
if(localStorage.getItem("P") == ""){
when localStorage is not set, it returns null. So the check would need to be a truthy check ( or you can check for nullv)
if(!localStorage.getItem("P")){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>le epic web page</title>
</head>
<body>
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
</body>
<script>
const Default =
"P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if (
localStorage.getItem("P") === "" ||
localStorage.getItem("P") === null ||
localStorage.getItem("P") === undefined
) {
localStorage.setItem("P", Default);
} else {
let currentValue = document.getElementById("txt");
currentValue.value = localStorage.getItem("P");
}
function save() {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
}
window.onbeforeunload = function () {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
};
</script>
</html>

Get current input value in function that is set as variable within another function. (I AM STUMPED) code examples within

I have a difficult question, I am trying to get the input value of an input field, however, I need this to happen within another function.
I already have code that works outside of this other function but I need to refactor it to work inside another function that I am calling.
Examples of working code and non-working code are below.
Here is the HTML where I am getting the input:
<!DOCTYPE HTML>
<HTML>
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript">
(function () {
var config = {
baseUrl: "js",
};
var dependencies = ["otherFile"];
require(config, dependencies);
})();
</script>
</head>
<body>
<div>
<label>Input URL</label>
<input type="url" />
<p id="targetInput"></p>
</div>
</body>
</html>
Here is the non-working JS that I am trying to call within another function:
function someOtherFunction() {
var getCurrentInput = function() { };
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
var getCurrentInput = function (e) {
log.currentInput = e.target.value;
};
}
});
Lastly here is the working code that works outside of the scope of someOtherFunction
var getCurrentInput = "";
var input = document.querySelector("input");
var log = document.getElementById("targetInput");
input.addEventListener("input", getCurrentInput);
function getCurrentInput(e) {
log.currentInput = e.target.value;
}
Now you may notice that there isn't a form being submitted here, the reason for this is because this code is running on an iframe that is being called into another app. The submit is happening there but requires me to call a function to make it happen and technically isn't a submit, meaning I don't have control over it like a regular submit. This is why I need to call the current input value inside someOtherFunction.
Any help would be greatly appreciated here! Essentially I want to get the value inside the input and update my API with the value as a JSON string. There must be a better way!
Was a bit difficult to follow at first given the nesting, but something like this?
const doThing = (e) => {
let input = document.getElementById("input");
let log = document.getElementById("targetInput");
log.textContent = input.value;
}
<div>
<label>Input URL</label>
<input type="url" id="input"/>
<p id="targetInput"> </p>
</div>
<button onclick="doThing()">Click</button>
Essentially an external submit that takes an internal input value, and injects it into another internal element?

How to make a not bootable counter when refreshing the web page?

I want to make a counter remains dynamic and non-bootable when updating
web page,
here is my code the problem is that when I refresh the page the counter(setTimeout) will count again from zero to 5 I want it to count from the last value before
the refresh
<html>
<head>
<meta charset="utf-8"/>
<title>Insert title here</title>
</head>
<script type="text/javascript">
setTimeout(function(){document.getElementById("tm").style.display='block'},
5000);
</script>
<body>
<form id="customer" action="/htmlvalidation" method="post">
<div>
<label>Time</label>
<input id="tm" type="text" style="display: none;"/>
</div>
<div>
<button type="submit">Add Customer</button>
</div>
</form>
</body>
</html>
thank you
You will have to manually store the counter value in the client's browser; by default, browsers will not retain any of a webpage's state when it is closed (or refreshed). For example, you may use the localStorage API:
const STORAGE_KEY = 'counter';
const TARGET_ELEMENT_ID = 'counter-div';
const INTERVAL = 1000;
const INC = 1;
// Notice the '+' below to make sure val is a number.
let val = +localStorage.getItem(STORAGE_KEY) || 0;
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
setInterval(() => {
val += INC;
localStorage.setItem(STORAGE_KEY, val);
document.getElementById(TARGET_ELEMENT_ID).innerHTML = val;
}, INTERVAL);
Here is a working example on codepen (it seems stackoverflow's snippets do not support localStorage).
(I didn't use your snippet because I wasn't sure what you were trying to do).
You could store the last timer iteration using localStorage before the user closes or navigates away from the tab, and resume when needed.
More about localStorage

Passing a var to another page

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
});

Categories