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));
});
});
Related
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.
I have a textbox on a web page. I would like to get the value of a URLs hash e.g. 12345 and place it as the value of the textbox upon loading the page (if there is a value), otherwise, I would like the textbox to remain blank.
I have tried using this code:
var hash = window.location.hash.substr(1);
function onoff(){
// pre-fill chat id textbox
if(hash){
var hash_value = window.location.hash.replace('#','');
document.getElementById("chat").value = hash_value;
} else {
document.getElementById("chat").value = '';
}
}
And in the html code(I am having trouble in calling the function).
<input type="text" id="chat" maxlength="5" required="">
If I were to change the value of the hash, would it be possible to have this fill the text box on load?
Sure thing! Just pass your function into window.onload:
var hash = window.location.hash.substr(1);
window.onload = function onoff(){
// pre-fill chat id textbox
if(hash){
var hash_value = window.location.hash.replace('#','');
document.getElementById("chat").value = hash_value;
} else {
document.getElementById("chat").value = '';
}
}
<input type="text" id="chat" maxlength="5" required="">
Hope this helps! :)
Execute your function on DOMContentLoaded. Note that this function can be limited to this:
function onoff(){
document.getElementById("chat").value = window.location.hash.substr(1);
}
document.addEventListener("DOMContentLoaded", onoff);
To also capture pure changes to the hash (in which case the page is not reloaded), also capture the corresponding hashchange event:
window.addEventListener("hashchange", onoff);
So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.
As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?
If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>
Please look at the following code. When the form gets submitted, is it actually submitting the values I have entered i.e. val(50) or at the point it serialzies does it just get data from the form on the actual html page?
// stop all forms from submitting and submit the real (hidden) form#order
$('form:not(#order)').submit(function(event) {
alert($(this).attr('id'));
//event.preventDefault();
if($(this).attr('id')==='quick2a'){
alert('quick2a being submitted');
//submitQuick2a();
$('form#order input[name=custom_channels]').val(50);
var name = 'het-';
name += $('form#order input[name=platform]').val('astsk');
name += '-ga-';
name += $('form#order input[name=license]').val('floating');
$('form#order input[name=productname]').val(name);
$.post('/store/cart/add/ajax/', $('form#order').serialize(), function() {
document.location.href = '/store/checkout';
});
}else{
//
}
I want those values to be set in the form regardless of what is set by the user, am I doing this correctly?
Thanks all
Why not just construct the data directly instead of stuffing it into a form and then grabbing the values via serialize?
$('form').submit(function(event) {
if($(this).attr('id')==='quick2a') {
var data = {
'custom_channels': 50,
'platform' : 'astsk',
'license' : 'floating',
'productname' : 'het-astsk-ga-floating'
};
$.post('/store/cart/add/ajax/', data, function() {
document.location.href = '/store/checkout';
});
}else{
//
}
return false;
});
It gets the values from the HTML page... but by calling .val(...) you're setting the values on the HTML page, so your code will work as you want it to.
Im trying to set the action of a form with javascript!
How come it wont work on this code: (what happens is that the page gets submitted to itself, as in 'action="#"'
function validateForm() {
var nr_of_pics=document.getElementById("annonsera_nr_pics").value;
var name = document.getElementById("annonsera_name");
var tel = document.getElementById("annonsera_tel");
var email = document.getElementById("annonsera_email");
var area = document.getElementById("annonsera_area");
var community = document.getElementById("annonsera_area_community");
var category = document.getElementById("annonsera_category");
var subcats = document.getElementById("annonsera_subcats").getElementsByTagName("select");
var headline = document.getElementById("annonsera_headline");
var description = document.getElementById("annonsera_des");
var price = document.getElementById("annonsera_price");
if (nameValid(name) && telValid(tel) && emailValid(email) && areaValid(area) && communityValid(community) && categoryValid(category) && subcatsValid(subcats) && headlineValid(headline) && descriptionValid(description) && priceValid(price)){
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
alert (form);
return true;
}
return false;
}
and the form:
<form name="annonsera" id="annonsera" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
BY the way, the alert box wont show up either!
ALSO, setting the form action manually in HTML works fine, and the form is validated properly!
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
These lines aren't doing what you seem the think they're doing.
The first line is creating a variable called 'form', and copying the form's current action into that variable as a string. The second line then sets the variable to a new value, but the form's action isn't being changed because the variable only contained a copy of the form's action.
This would be what you're after:
var formElement = document.getElementById("annonsera");
formElement.action = "bincgi/verify_"+category+".php";
However, I don't know why your alert box isn't showing up at all. Are you certain that all the validity methods are actually being passed?
Try this:
document.getElementById("annonsera").action = "bincgi/verify_"+category+".php";
The problem with your code is that you first read the action attribute into a variable:
var form = document.getElementById("annonsera").action;
and then you set the form variable to a new string but this won't update the value of the DOM element.
Give it simple like
document.annonsera.action = "bincgi/verify_"+category+".php"
and to Submit the form
document.annonsera.submit()