I am trying to re-populate the saved form inputs after a submit/page reload. The problem I'm running into is the input field populates the saved value (or just any string) but then resets almost immediately. What am I missing? Thanks
Flask (Server):
#app.route("/code", methods=["GET", "POST"])
def code():
value = request.form["field1"]
return render_template(
"code.html",
saved_inputs = value
)
Html:
<form action="{{ url_for('code') }}" method="post" id="form">
<label for="field1">Test Input 1 </label>
<input type"text" name="field1" id="field1">
<button type="submit" class="btn btn-primary" id="btnSubmit">Submit</button>
</form>
JS:
<script>
$("#form").on('submit', function(event){
event.preventDefault();
// convert form to JSON
var formData = new FormData(document.getElementById('form'));
var formJSON = {};
for (var entry of formData.entries())
{
formJSON[entry[0]] = entry[1];
}
result = JSON.stringify(formJSON)
console.log("results is: "+result);
// set JSON to local Storage
sessionStorage.setItem('formObject', result);
// submit form
document.getElementById("form").submit();
// decode sessionstorage object
var decodedObj = JSON.parse(sessionStorage.getItem('formObject'));
console.log("sessionStorage object: "+decodedObj);
// alert("value is: "+decodedObj["field1"]);
// alert("jinja value is: "+"{{ saved_inputs }}");
// retrieve localStorage and populate input
// this is not working as expected
document.getElementById("field1").value = "WHY ISN'T THIS SAVING??";
// document.getElementById("field1").value = '{{ saved_inputs }}';
})
</script>
I think the issue you are facing is that you are not checking when the page loads--only when the form is submitted. To load the form on page load we can use sessionStorage to check if the record exists and then load the object to the form.
$(function() {
const formObj = sessionStorage.getItem('formObject');
// Load object
if (formObj != null) {
console.log("Previous form session exists")
let decodedObj = JSON.parse(formObj);
console.log("sessionStorage object: " + decodedObj);
console.log("value is: " + decodedObj["field1"]);
// retrieve sessionStorage and populate input
console.log("Loading previous session");
document.getElementById("field1").value = decodedObj["field1"];
}
});
Proof of concept fiddle
You can try storing the values in local storage & then retrieve them whenever the page is reloaded. You have used Session Storage. See.
Related
In a wordpress website I want that when someone fills a product form (select attributes etc) and clicks buy now, if is not logged in then he is redirected to login form. On succesfull login I want to get the submitted form contents from localstorage, fill the form and then submit the form automatically.
Is that possible?
I found that I can store the submitted form like this (but how I can refill the form automatically?):
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var formFields = $(this).serialize();
localStorage.setItem('myForm', formFields);
//data = localStorage.getItem('myForm'); //retrieve it later
});
});
You should be able to retrieve data from localStorage, get your form fields using DOM selectors and fill their values using the data from localStorage.
In vanilla JS, you can probably do the following:
document.addEventListener('load', () => {
// check if user is logged in according to your usecase
if(isLoggedIn()) {
try {
const formData = JSON.parse(localStorage.getItem('myForm'));
// get input fields. If you have some unique id associated to them, you can use document.querySelector(`#${inputId}`);
const inputFields = document.querySelectorAll('input');
for(let i = 0; i<inputFields.length; i++) {
const inputId = inputFields[i].getAttribute('data-id');
// fallback to empty string in case it is not found in localStorage object
inputFields[i].value = formData[inputId] || '';
}
} catch(e) {
// handle error
}
// Now you have the form input fields pre-filled, add custom logic from here ..
}
})
/*
--- Sample DOM ----
<input data-id="name" />
<input data-id="city" />
---- Form fields saved in localStorage ---
{ name : 'Naruto', city: 'Leaf Village' }
*/
I have a form where it has a default value name "Alex". My goal is to save any changes made to the form through session Storage. It seems like my storage is getting saved on the browser, but my values are not updating in the form. On page refresh it keeps going back to the default value "Alex". I am not sure why that is happening if my values are being stored on the browser. Is my event handler the right approach for this?
JS Fiddle : https://jsfiddle.net/2yL7k8w5/20/
document.addEventListener("change", (evt) => {
const save_name = document.getElementById("name").value;
sessionStorage.getItem("name");
sessionStorage.setItem("name", save_name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
crossorigin="anonymous"></script>
<div class="well">
<form action="/person.php" method="post">
<label for="firstName">First Name</label>
<input id = "name"class="form-control" type="text" name="firstname" value="Alex">
</form>
</div>
I think the approach is okay but the problem is you've set value of input box in your HTML but you are not really updating the value with the value stored in sessionStorage.
So, use the following code to see the change:
let sname = sessionStorage.getItem("name");
let name = document.getElementById("name");
if(sname) {
name.value = sname;
}
document.addEventListener("change", (evt) => {
const save_name = name.value;
console.log(sessionStorage.getItem("name"));
sessionStorage.setItem("name", save_name);
});
You are saving in sessionStorage but you are not updating value on page load if session storage has any value in it.
Add below code.
$(document).ready(function() {
const name = sessionStorage.getItem("name");
if(name){
document.getElementById("name").value = name
}
})
I have this JavaScript code that processes and displays the value onto the same page; the value is entered using a textbox. I want to pass this value onto another page. this my code:
index.html:
<form action="display.html" method="post" id="name-form">
<p>
<label>Your full Name</label>:<br />
<input type="text" name="fullName">
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<!-- <p id="result"></p>-->
<script>
var form = document.getElementById('name-form');
form.onsubmit = function (e) {
e.preventDefault();
var result = document.getElementById('result');
result.innerHTML = 'Hi ' + form.fullName.value;
console.log(form.fullName.value);
this.reset();
};
</script>
display.html
<p id="result"></p>
<script>
var form = document.getElementById('name-form');
form.onsubmit = function (e) {
e.preventDefault();
var result = document.getElementById('result');
result.innerHTML = 'Hi ' + form.fullName.value;
console.log(form.fullName.value);
this.reset();
};
</script>
my question is how do I get the value that is entered into the textbox to display onto another page?
If you have a static website, you should consider storing that value in localStorage. So that value will be available all across your web pages.
And if you have a dynamic website you can store that value in db and then request db for that value when you're on some other page.
Choose anyone of the approaches that fits in your case and application.
Read here about localStorage
Use cookies.
Save the name: document.cookie = "name=" + name
Load the name: name = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");
See here for a simpler way to load cookies
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
Help me please:
I have a dynamic part of a module (generated by php application), for example:
<input type="text" class="attr" name="Input_0"/>
<input type="text" class="attr" name="Input_1"/>
...
<input type="text" class="attr" name="Input_n"/>
The value n is random (n> = 1). Obviously at the bottom of the form there's a submit button that confirms the completion of fields.
So, I need a procedure to read the modified values of the input tag via jquery script that gives this output:
Input_1 = value
Input_5 = value
...
Input_n = value
How can I do this?
here is some sample code :
var $inputs = $('#form_id :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
Try serializing the form data and looping through the inputs and their values:
$('form').submit(function(e) { // when we submit the form
e.preventDefault();
// loop through form data and print values
var data = $.each($(this).serializeArray(), function(i, value) {
console.log(value);
});
});
Check out this fiddle: http://jsfiddle.net/kukiwon/ECz52/