How to retain value after page refresh? - javascript

I managed to get the number go up after pressing each button, but I need the value to stay after refreshing the page. I understand I could use localStorage, but I do not understand how it works.
<form>
<input type="text" id="number" value="0" />
<input type="button" onclick="incrementValue10()" value="$10" />
<input type="button" onclick="incrementValue20()" value="$20" />
<input type="button" onclick="incrementValue50()" value="$50" />
</form>
function incrementValue10() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value += 10;
document.getElementById('number').value = value;
}
function incrementValue20() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value += 20;
document.getElementById('number').value = value;
}
function incrementValue50() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value += 50;
document.getElementById('number').value = value;
}

To use localStorage you simply need to call setItem() to save a value and getItem to retrieve it.
It's also worth noting that you should not be using onX attributes. They are bad practice. Use unobtrusive event handlers instead. Also, you can easily DRY the code up by attaching a single function to all elements and varying its action by a data attribute on each one. Something like this:
let output = document.querySelector('#number');
// save the value on click of the button
document.querySelectorAll('.inc').forEach((el) => {
el.addEventListener('click', function() {
var newValue = parseFloat(output.value) + parseFloat(this.dataset.inc);
output.value = newValue;
localStorage.setItem('number', newValue);
});
});
// retrieve the value when the page loads
var oldValue = localStorage.getItem('number') || 0;
output.value = oldValue;
<form>
<input type="text" id="number" value="0" />
<input type="button" class="inc" data-inc="10" value="$10" />
<input type="button" class="inc" data-inc="20" value="$20" />
<input type="button" class="inc" data-inc="50" value="$50" />
</form>
Note that SO snippets block access to localStorage, so here's a fully working jsFiddle

You can use localstorage for this:
if(localStorage.getItem('number') != ""){
document.getElementById('number').value = localStorage.getItem('number');
}
function incrementValue10()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value+=10;
document.getElementById('number').value = value;
localStorage.setItem('number', document.getElementById('number').value)
}
function incrementValue20()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value+=20;
document.getElementById('number').value = value;
localStorage.setItem('number', document.getElementById('number').value)
}
function incrementValue50()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value+=50;
document.getElementById('number').value = value;
localStorage.setItem('number', document.getElementById('number').value)
}

As per the code, you are just storing the values in memory(heap). When page is re-loaded browser just allocates new memory and you can't retain the previous values. So store the values in some persistence like client side(localstorage, sssionstorage and Index DB) if it is entirely related to the particular client's UI state, servr side Databases like SQL, NoSQL, RDBMS.
Refer this link for basic understanding of client side storage.
https://www.w3schools.com/html/html5_webstorage.asp

Related

Remove 10 from input type text

So I have this HTML Code
var number = document.getElementById("number");
function ClickFunction() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function Grandma() {
number.value = number.value - 10;
}
<input type="text" id="number" class="input-text-no-border-font-size-30-centered" value="0" />
<input type="button" onclick="ClickFunction()" value="Klick mich!" class="input-button-centered-box-general">
<p align="right">
<input type="button" onclick="Grandma()" value="Kosten: 10 Cookies -> Die Großmutter (macht ein klick mehr)" class="input-button-right-box-general">
</p>
As you can maybe see i am working on a cookie clicker game. I want to make a Grandma that removes 10 from the current amount of cookies and so makes the user per click 2 cookies instead of one. I am fairly new tho. Any help is greatly apreciated
Small Edit: I dont know why but somehow the code works here on stack overflow but not on my local Website
If you want to increase the cookie value every time grandma get 10 then:
var number = document.getElementById("number");
var incremental = 1
function ClickFunction() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value = value + incremental;
document.getElementById('number').value = value;
}
function Grandma() {
number.value = number.value - 10;
incremental ++
}
you can use Replace function. As your input is a string.

how to increase a input value via button click and also update this value in server site

I think, hopefully I will find the answer.
Thank you.****
Increase
This is how you can update the value of the input when clicking on a button. Hope this helps.
const incrementValue = () => {
let value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
<form>
<input type="text" id="number" value="0"/>
<input type="button" onclick="incrementValue()" value="Increment Value" />
</form>

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

How to manipulate value based on textbox value?

If I enter negative value in textbox, while in onclick the value will be reduced by some other value.
If I enter positive value in textbox, while in onclick the value will be add by some other values.
Make a simple comparison.
function go() {
var value = parseFloat(document.getElementById("value").value),
positiveValue = 5,
negativeValue = -1;
value += value < 0 ? negativeValue : positiveValue;
document.getElementById("value").value = value
}
<input id="value" onchange="go()">
Change the value of the textbox comparing it on button click.
HTML :
<input type="text" id="inputTextBox" />
<input type="button" id="changeButton" value="update value"/>
javaScript :
var paddingValue = 10;
document.getElementById("changeButton").onclick = function(){
var inputTextBox = document.getElementById("inputTextBox");
if(inputTextBox.value < 0){
inputTextBox.value = parseInt(inputTextBox.value) - paddingValue;
}else{
inputTextBox.value = parseInt(inputTextBox.value) + paddingValue;
}
};
jsFiddle demo

not changing textbox value from ui and unable to display

taking value in 1st textbox and want to display it in 2nd..
1st <input type="text" value=" " id = "marks1" name = "marks1" onblur = "myFunction('marks1')" />
2nd <input type="text" value=" " id = "marks2" name = "marks1" disabled = "disabled" />
and on oblur I am calling a function. Whenever I change the value from UI, on function call I am getting the old value i.e. ' ' instead of changed value.
in the variable "value" the old value which i am getting, i am unable to display it on 2nd textbox.
function myFunction( txtname )
{
alert("call");
var txtobj = document.getElementsByName(txtname);
var value = txtobj[0].value;
alert("my value : "+value);
txtobj[1].value = value;
}
I know the code is okay, but it is not working at me. Is there any other way?
Works for me:
function myFunction(element)
{
var txtobj = document.getElementsByName(element);
var value = txtobj[0].value;
txtobj[1].value = value;
}​
http://jsfiddle.net/pwTwB/1/
Are you getting an error?
Try it this way:
function myFunction( txtname )
{
var txtobj = document.getElementById(txtname);
var target = document.getElementById("marks2");
target.value = txtobj.value;
}
Here is a simple way to set the next textbox's value.
function moveText(ele){
document.getElementById("marks2").value = ele.value;
}
Then use the following in your html markup
<input type="text" id="marks1" onblur="moveText(this)" />
<input type="text" id="marks2" disabled="disabled" />

Categories

Resources