Keep form data with back button - javascript

there are many questions similar to this but none of them seem to help with my situation.
I am developing a three step process using Javascript and html
I have 2 forms in the first two steps.each with a next/prev button
I need to be able to go back from step two back to step 1 and still have step ones form data in the fields. I am rather new to javascript any help would be appreciated. I am unsure how to save the form data and then insert it when the user goes back from step 2
EDIT:
I have decided to use JS to hide/show forms, please can someone tell me why my variable never gets to currentStep == 3; this causes issues when going back as it goes back to step one becasue the currentStep value is stuck at 2
var currentStep = 1;
function nextStep() {
if (currentStep ===1){
$("#petmain1").hide();
$("#petmain2").show();
$("#addproduct").show();
$("#firstimage").hide();
$("#secondimage").show();
currentStep = 2;
console.log("Current step is " + currentStep);
}else if(currentStep ===2){
$("#petmain2").hide();
$("#addproduct").hide();
$("#secondimage").hide();
$("#petmain3").show();
$("#thirdimage").show();
$("#firstimage").hide();
currentStep === 3;
console.log("Current step is " + currentStep);
}
}
function prevStep() {
if (currentStep ===2){
$("#petmain1").show();
$("#petmain2").hide();
$("#addproduct").hide();
$("#firstimage").show();
$("#secondimage").hide();
currentStep = 1;
console.log("Current step is " + currentStep);
}else if(currentStep === 3){
$("#petmain3").hide();
$("#thirdimage").hide();
$("#secondimage").show();
$("#petmain2").show();
$("#addproduct").show();
currentStep === 2;
console.log("Current step is " + currentStep);
}
}

You can use localStorage
On navigating from first step to second step you can store the value
if(typeof(Storage) !== "undefined") {
localStorage.setItem("someKey", $("#somField").val());
} else {
//
}
Again on navigating from second to first step check the local storage for the value and assign it to the fields in first form
$("#somField").val(localStorage.getItem("someKey"))

You may use sessionStorage.
HTML
<form>
Username : <input type='text' id='name'> <br />
Password : <input type='password' id='password'> <br />
<input type='button' onclick='storedata()' value='submit'>
</form>
<p id='res'></p>
JS
window.onload = function() {
if (sessionStorage.name && sessionStorage.password) {
document.getElementById("name").value = sessionStorage.name;
document.getElementById("password").value = sessionStorage.password;
}
};
function storedata() {
if(typeof(Storage) !== "undefined") {
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
sessionStorage.name = name;
sessionStorage.password = password;
document.getElementById("res").innerHTML = "Your datas restored";
} else {
document.getElementById("res").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Working Demo : https://jsfiddle.net/d83ohf6L/

Related

How do I store if a user clicked a button on a cookie using JavaScript?

I'm trying to make a simple website for a friend. The purpose is picking a ticket and showing an alert and disabling the button showing that the ticket has been already redeemed. I also want to store that on a cookie, because if my friend leaves the webpage, the values are restored to default and not based on the choices my friend have made.
The HTML code is this:
<img id="first_ticket" src="ticket_not_edited.png" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="first()">Redeem</button>
The JavaScript code is:
function first() {
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background='#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src='broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
The purpose is to store the user's choice on a cookie so I can always check what my friend has chosen to disable the ticket and the button availability.
Also, how can I make it to check if my friend chose a ticket to disable some options (by "some options" I'm referring to disabling the button and changing the image to a broken ticket"?
Thanks in advance!
You can use document. cookie to store the answer, and you can check in the link below to know if it exists.
Got it from here:
final:
<img id="first_ticket" src="" width="50%">
<br>
<button id="first_button" class="ticket1" onclick="checkIfExists()">Canjear</button>
<script>
// check if it Exists
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
var myCookie = getCookie("first");
if (myCookie == null) {
alert('Welcome! Please Choose A ticket below.');
}
else {
alert('Welcome back! You already choose a ticket!');
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
function checkIfExists() {
if (myCookie == null) {
document.cookie = "first = 'yes'";
alert("You've redeemed successfuly the first ticket.");
document.getElementById("first_button").style.background = '#FF0000';
document.getElementById("first_button").disabled = true;
document.getElementById('first_button').src = 'broken_ticket.png';
document.getElementById('first_button').innerHTML = "REDEEMED";
}
else {
alert('Oh. You already choose a ticket.');
}
}
</script>

Cannot get cookie value

I have a script that calls a prompt when I push a button and gets a number from the user. The number is stored in a cookie. Then that script loads a view that gets the number from the cookie and passes it to a form.
Currently I have the cookie being saved; I can see it in the browser debugger. But when I try to get the cookie in my view it always returns null.
I think the request sends a cookie with a null value before updating the cookie.
JavaScript
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
// $(".on_button").click(function() {
var amount = prompt("Please enter amount of orders" ,"0")
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
document.cookie = "amount=" + amount; //+ ";max-age=60";
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});
View
def add_order(request, meal_slug, meal_restaurant):
print("OK")
amount = get_server_side_cookie(request, 'amount', '1')
print(amount)
//clear_amount_cookie(request)
if amount is not None:
meal = Meal.objects.get(
slug=meal_slug, restaurant_slug=meal_restaurant)
user = UserProfile.objects.get(user=request.user)
order = Order.objects.create(
meal=meal, customer=user, amount=amount, date=datetime.now())
order.save()
//clear_amount_cookie(request)
return redirect('food_cloud:index')
Get cookie function
def get_server_side_cookie(request, cookie, default_val=None):
val = request.COOKIES.get(cookie)
print(val) //This is where I see the null value
try:
int(val)
except (ValueError, TypeError):
val = default_val
print(val + " here")
return val
I solved the problem by implementing the jquery.cookies.js objects Link: https://github.com/carhartl/jquery-cookie
Then I replaced the code for creating the cookie. Apparently JQuery is not good for handling cookies directly
Changed code
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
var amount = prompt("Please enter amount of orders" ,"0");
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
Cookies.set('amount', amount) //This is the new code for creating cookie
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});

Replace previously generated content in Javascript based on user input

I have a button on that perfroms the collatz conjecture with the push of a button, and takes in the user's input. It then prints out the steps as a list into a p tag. I wanted to know how I would override the previously created steps, as I have noticed calling the method again adds to the end of the previous list.
The main reason I'm using a list is for readability, so I don't want to get rid of it unless there's a better way of doing this.
//collatz function
function collatz (){
var step = 0;
var inputCollatz = prompt("What number do you want to add?")
if (inputCollatz <= 1){
document.getElementById("collatz").innerHTML = "No steps required, already less than or equal to 1.";
}
else if(isNaN(inputCollatz)){
document.getElementById("collatz").innerHTML = "Please add a number.";
}
else if (inputCollatz.toString().indexOf('.') != -1){
document.getElementById("collatz").innerHTML = "Whole numbers please!";
}
else{
while(inputCollatz > 1){
//needed help w/ ternary operators, still need practice with it
inputCollatz = inputCollatz % 2 ? 3 * inputCollatz + 1 : inputCollatz / 2;
step++;
var item = document.createElement("li");
var text = document.createTextNode(inputCollatz);
item.appendChild(text);
var list = document.getElementById("collatz");
list.appendChild(item);
}
document.getElementById("steps").innerHTML = "Number of steps: " + step.toString();
}
}
This is the button in html.
<button onclick="collatz()">Find the number of steps.</button><br/>
<br/>
<div id="collatz"></div>
<br/>
<div id="steps"></div>
I was suggested to clear out the collatz div before each loop, which worked.
...
else {
document.getElementById("collatz").innerHTML = '';
while(inputCollatz > 1) {
....

How to setup a list with removable items that stores itself in localStorage in javaScript

I have been working on a little project and I need some values to be stored in an array, that would be displayed at all times, even if the page reloads, and that could be removed by pressing a button.
The idea that I had is to store the array in localStorage, and every time the page loads, they get downloaded into the javascript array.
That seems to work flawlessly, but my problems come when I am trying to remove them by pressing a button. I know where the problem in my code is, I just don't know how to do it so that it works.
The problem is that, after I delete an item with a low index, it messes with my ability to later delete items with higher index.
Here's the code:
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete(deleted) {
var index = deleted;
a.splice(deleted, 1);
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
If anyone could help, It would be Amazing!
I didn't test the code but I think this can help you out!
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push({
index: a.length,
data: "<p>" + input.value + " </p><button onclick='Delete(" + a.length + ")'>Delete</button><br />"
});
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete (deleted) {
a = a.filter(function (e) { return e.index !== deleted })
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
Your problem is with this
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
You're hardcoding the index to delete in the Delete button, but the index can change if you delete an item from earlier in the array.
You could consider re-rendering everything, including the buttons, every time your array changes.
Another alternative is that every item in your array can have an ID, and that would not change when an earlier one is deleted. Then you can make your 'delete' function remove an element from the array based on its ID.
One more solution: make the button click function check it's own index upon click (eg check if it's the 2nd delete button or the 9th delete button), and delete from the array the index that it gets from that check. That way you can keep most of your code the same, but the index isn't hardcoded into the button, it's live-checked every time.

Number Guessing Game using while loop

In this project, I need to set a maximum of 10 guesses, an indication of what number is being guessed and keep those results on the screen at the end of each game without overwrite the previous guesses.
Each set of guess output needs to be numbered to indicate how many guesses have been made. For the output, I need to use innerHTML. The user will guess a number from 1 to 999. I have to use while loop.
So far this is the code where I'm working and I have some errors and it's not working. Can anybody put me in the right direction to finish this code?
The errors that I found when I inspect the document are checkGuess() function and an anonymous function with a message "Cannot read property 'value' of null"
<script type="text/javascript">
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.getElementById("guesses");
var lastResult = document.getElementById("lastResult");
var lowOrHi = document.getElementById("lowOrHi");
var guessSubmit = document.getElementById("guessSubmit");
var guessField = document.getElementById("guessField");
var guessCount = 1;
function checkGuess() {
var userGuess = Number(guessField.value);
guesses.innerHTML += userGuess + "";
}
while (guessCount == 10) {
lastResult.innerHTML = "!!!GAME OVER!!!";
disableForm();
} else {
if (userGuess == randomNumber) {
lastResult.innerHTML = "Congratulations! You got it right!";
lowOrHi.innerHTML = "";
disableForm();
} else {
lastResult.innerHTML = "Wrong!";
if (userGuess < randomNumber) {
lowOrHi.innerHTML = "Your guess is too low!";
} else if (userGuess > randomNumber) {
lowOrHi.innerHTML = "Your guess is too high!";
}
}
guessCount++;
guessField.value = "";
}
}
function disableForm() {
var wholeForm = document.querySelector(".form"); // grab a reference to the whole form (the contents of the div with class form)
wholeForm.style.opacity = 0.5; // change the opacity of the form to 0.5
guessField.setAttribute("disabled", "disabled");
guessSubmit.setAttribute("disabled", "disabled"); // disable the form field and submit button so they can no longer be used
}
guessSubmit.onclick = checkGuess;
</script>
</head>
<body>
<h1>Number guessing game</h1>
<p id="guesses"></p>
<p id="lastResult"></p>
<p id="lowOrHi"></p>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit">Enter Guess</button>
</div>
<p></p>
</body>
</html>
Your program is all wrong and is actually doing nothing
the only thing that actually executes is everything outside your functions,
and those are being called only when the page is loaded for first time
in order to execute your CheckGuess you need to actually call it :
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
but everything else that is actually outside of your functions are only executed when the page is loading
also you have a while--else statement, that's not even possible
then again... it is outside a function so it is useless
You need to put everything on one single statement
YOU DO NOT NEED A WHILE
once you write something down on the page it will stay there until it reloads
if you write a while like that you will just loop your code endless.
this code and logic is so wrong in so many ways i will sent you a functional code :
<script type="text/javascript">
var guesscount =0;
var randomNumber = Math.floor(Math.random() * 100) + 1;
function checkGuess()
{
guesscount = guesscount +1;
var userGuess = document.getElementById("guessField").value;
document.getElementById('guesses').innerHTML += Number(userGuess)+ '<br>';
CheckResults();
}
function CheckResults()
{
//add here your logics if the number is wrong
if ( guesscount>= 10)
{
document.getElementById("guessField").disabled = true;
document.getElementById("guessSubmit").setAttribute('disabled', 'disabled');
document.getElementById('guesses').innerHTML += 'game Over !';
}
}
</script>
</head>
<body>
<h1>Number guessing game</h1>
<label id="guesses"></label>
<label id="lastResult"></label>
<label id="lowOrHi"></label>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
</div>
<p></p>
</body>
</html>

Categories