I am replicating a grocery store webpage for a course project and would like to know how to keep the value in the quantity box even after the webpage has been refreshed.
<button type="button" id="subtract" onclick="decrease()">-</button>
<input class="quantity-box" type="text" id="text" value="0">
<button type="button" id="add" onclick="increase()">+</button>
<script>
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value>0){
textBox.value--;
}
}
function increase(){
var a = 1;
var textBox = document.getElementById("text");
textBox.value++;
}
</script>
Note: I am able to use AJAX, but I am not familiar with this so if it is included in the solution a brief explanation would suffice. HTML/JAVASCRIPT/CSS/AJAX
You may use cookies, create two functions of setting and getting the cookies, and then use them for setting the value of quantity in cookies, you will have to get the quantity cookie while loading the web page as you need to set the quantity value even if the page is reloaded.
here is an example about how can you achieve what you want to do. cheers...
window.onload = function(){
document.getElementById("text").value = getCookie("quantity");
}
function decrease() {
var currentValue = document.getElementById("text").value;
if (currentValue > 0) {
document.getElementById("text").value = --currentValue;
setCookie('quantity', currentValue);
}
}
function increase() {
var currentValue = document.getElementById("text").value;
currentValue = currentValue? currentValue: 0;
document.getElementById("text").value = ++currentValue;
setCookie('quantity', currentValue);
}
function setCookie(name, value) {
var d = new Date();
var days = 10; // expires in days
d.setTime(d.getTime() + (days*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
function getCookie(name) {
var name = name + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
<button type="button" id="subtract" onclick="decrease()">-</button>
<input class="quantity-box" type="text" id="text" value="0">
<button type="button" id="add" onclick="increase()">+</button>
Also you may use localStorage
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value > 0){
textBox.value--;
localStorage.setItem('quantity', textBox.value);
}
}
function increase(){
var a = 1;
var textBox = document.getElementById("text");
textBox.value++;
localStorage.setItem('quantity', textBox.value);
}
window.onload = function() {
var textBox = document.getElementById("text");
textBox.value = localStorage.getItem('quantity');
}