Save html form field state - javascript

Today I came up with something interesting at one of my projects. I have a search box with several fields(ex.: licence plate, date of buy, state) and some of them has an operator field. (ex.: >, <, =)
After I post my search and returns the result say it i want to change one of my operators but always changes to the first element of it. Is there anything that i can do to "save" the state of the fields?
I could do it with sessions but it is a fairly big form so it would be ugly.
Thank you for your answers!

A small snippet for you using localStorage:
I have timed as 5 seconds to take a backup of everything on the form.
Loads the stuff from the localStorage once the page is loaded.
window.onload = function () {
if (typeof(Storage) !== "undefined") {
if (typeof localStorage["name"] !== "undefined") {
document.getElementById("name").value = localStorage["name"] ? localStorage["name"] : "";
document.getElementById("pass").value = localStorage["pass"] ? localStorage["pass"] : "";
}
// Code for localStorage/sessionStorage.
setInterval(function () {
document.getElementById("saving").innerHTML = 'Saving...';
setTimeout(function () {
document.getElementById("saving").innerHTML = '';
}, 500);
localStorage.setItem("name", document.getElementById("name").value);
localStorage.setItem("pass", document.getElementById("pass").value);
}, 5000);
}
};
strong {display: inline-block; width: 50px;}
<form action="">
<strong>Name:</strong> <input type="text" name="name" id="name" /><br>
<strong>Pass:</strong> <input type="password" name="password" id="pass" /><br>
<span id="saving"></span>
</form>
Note: localStorage is a sandboxed feature in snippets. So doesn't work here. Check in JSBin: http://output.jsbin.com/bubukunoke

I solved the problem with sessions at the end.
When I post the form I save all of the content into a session and in the View I check if it exists and if yes I set it to as the field value.

Related

Show value of an input form from a page into another page with pure Javascript

I have two different pages. In the first one I have a form with name and email, and the second page should be the result page, and I want to show dynamically the name and email of the user from the form of the first page in the second page, and I precise, I want all this in pure javascript, not php. I tried the localStorage method, and this is what I got so far:
First page: Form page
HTML:
<label>Name:</label>
<input type="text" id="name" />
<label>Email</label>
<input type="text" id="email" />
<button onclick="testVariable()">Submit</button> <br />
Javascript
function testVariable() {
var strText = document.getElementById("name").value;
var strText1 = document.getElementById("email").value;
var result = strText + ' ' + strText1;
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("programX").textContent = result;
}
}
Second page:Result page
HTML:
<p>Hi
<span id="result"></span> thank you for subscribing to our service
</p>
Javascript:
// Check browser support
if (typeof(Storage) !== "undefined") {
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("programX");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
localStorage does not have any textContent property.
To set a localStorage
localStorage.setItem('key', 'value');
To get a localStorage value
localStorage.getItem('key');
So, what you are doing to set localStorage is wrong.
Replace
localStorage.setItem("programX").textContent = result;
with
localStorage.setItem("programX", result);

Save form data in browser session

I have an div that is shown when a form is submitted, but when I refresh the page, my data disappears and I'm searching for a way to preserve my data on page refresh.
I know how to save data in a session, but not an entire form. How do I approach this issue? Is it even possible to save an entire form with Javascript?
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
} else {
div.style.display = 'none';
}
}
<form name="product_form" id="product_form" enctype="multipart/form-data" action="admin_products.php" method="post" accept-charset="utf-8" onsubmit="showHide();
return false;">
<input type="textfield" id="title" name="title" value="" readonly>
<div id='hidden_form' style="display:none">
<input type="text" id="name" name="name" value="" placeholder="Product Name">
<label id="option_1" name="option_1">Option Name</label>
<input type="text" id="optionn" name="optionn" value="" placeholder="Product Name">
</div>
<input type="submit" id="add" name="add" value="Save" class="" <!--onclick="myFunction()-->">
When you hit submit, you'll reload the page and lose your data. By using localStorage and JSON.stringify() you are able to save the data locally in your browser and fetch it when you load your page.
Since localStoragecan only store strings, you'll have to convert your object to a string. That's where JSON.stringify() comes into play. And when you fetch it, you can use JSON.parse() to convert it back to an object.
$("#btnSubmit").click(function() {
var data = {};
data.Text = $("#myText").val();
data.isProcessed = false;
localStorage.setItem("myData", JSON.stringify(data));
});
//On load
var data = localStorage.getItem("myData");
var dataObject;
if (data != null) //There's stored data
{
dataObject = JSON.parse(data);
$("#myText").val(dataObject.Text)
localStorage.removeItem("myData"); //Remove data, otherwise it'll be there for a long time.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form method="post">
<input type="text" id="myText" />
<button type="submit" id="btnSubmit">Submit</button>
</form>
</div>
More information on localStorage: W3Schools
More information on JSON.stringify and JSON.parse: MDN
I don't know if the snippet will work, since it'll submit a post. Copy this snippet and try it on your local system.
EDIT
As I made a tiny mistake myself, I updated my snippet. But as I suspected, SO doesn't allow access to localStorage.
And ofcourse, you'll have to put this code in your $(document.ready(function() { ... }); for it to work. I did forget to add a <form></form> to my HTML snippet. And I just tested it on my local system and it's working fine.
You can try with localStorage. It's key-value storage that all modern browsers have. There're simple libraries to write to localStorage with fallback to cookies if you need old browser support (written by javascript instead of server side scripts).
I'll give you an example with localStorage:
//emulating that the form was showed (save clicked) and the value true stored on the localStorage
localStorage.setItem('displayedForm', true);
//initializing the state of the page
initialize();
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
localStorage.setItem('displayedForm', true);//if the conditions are meet to display the form, store it on the localStorage
} else {
div.style.display = 'none';
localStorage.setItem('displayedForm', false);//if the conditions are **NOT** meet to display the form, store it on the localStorage as well
}
}
function initialize() {
if (localStorage.getItem('displayedForm') === true || localStorage.getItem('displayedForm') === 'true') {
var div = document.getElementById("hidden_form");
div.style.display = '';
}
}
Working Fiddle: https://jsfiddle.net/y0uep73e/
Facing this problem myself, I wrote a simple library to automatically handle saving and loading form data via local storage: https://github.com/FThompson/FormPersistence.js
Example which saves data upon unload and loads data upon load:
<script src='https://cdn.jsdelivr.net/gh/FThompson/FormPersistence.js#1.0.1/form-persistence.min.js' type='text/javascript'></script>
<script type='text/javascript'>
window.addEventListener('load', () => {
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm)
})
</script>

Javascript can't locate HTML form ID

I'm creating a basic HTML form, and a Javascript form validator that looks for any input value in the "first name" field. The problem I'm having is that nothing seems to be working to return the first name form value to check it in JS.
Relevant HTML:
<form id="form1" name="formName">
First name:<br>
<input type="text" id="fn" >
<br>
Last name:<br>
<input type="text" name="ln" >
<br>
Email address: <span style="color:red">(required)</span><br>
<input type="text" name="email" >
<br><br>
<button onclick="validate()">Submit</button>
</form>
My JS:
var validate = function (){
var x = document.getElementById("fn").value;
if (x == null || "" || "undefined"){
alert("Please fill out your first name");
return false;
}
kickoff();
}
var kickoff = function () {
var visitor = document.forms["form1"].fn.value;
alert("Thanks for filling out, " + visitor +"\n");
return visitor;
};
Here's a JSFiddle.
My X variable is never reached, it seems, and keeps returning "undefined" when I submit the page. I've been fiddling with it for quite a while and can't seem to figure out what I'm doing wrong. Any help?
This doesn't mean what you think:
if (x == null || "" || "undefined") {
Can also be written as:
if ((x == null) || // might be false
"" || // will be false
"undefined" // will be true
) {
so the if will always be true.
You really just need:
if (! x) {
Besides the syntax issues, that method is also out-of-scope. You're not even going to be able to debug the issue with your conditional until you fix that.
You can either in-line the script higher up in the DOM or define validate directly on the window object:
window.validate = function () {
http://jsfiddle.net/frg37t3u/5/
Neither case is ideal, you should know. Globals are bad, but that's another discussion.

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

Submit form interfering with others

I have this email subscribe form for newsletter which gets delivered to me by email using PHP. It is located in footer which means that it is available on all pages across the website.
JSFIDDLE DEMO
Form works ok now but the problem is that it is interfering with other parts of website where forms are included - it messes those up and causes error to show on other fields as well.
My question is how do I isolate this form and script only for this part of the code so it will be defined only for this part of the webpage? What am I doing wrong?
As noted in the comments above,, you need to replace the "id" attributes in the html with "class" attributes. Then, modify your jQuery finders to search by class, constrained within the #subscribe form.
The HTML
<form id="subscribe" name="subscribe" action="#" method="post">
<input name="email" type="email" class="email" placeholder="Your e-mail adresss">
<span><button class="send" type="button">Subscribe</button></span>
</form>
And the Javascript
$(document).ready(function () {
$("#subscribe").submit(function () {
return false;
});
$("#subscribe .send").on("click", function () {
$('#subscribe input.error').removeClass('error');
var emailval = $("#subscribe .email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#subscribe .email").addClass("error");
}
var minlen = $('#subscribe input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
//you shouldn't need to change what you had here in the Fiddle; I didn't
//copy it for brevity's sake
});
}
});
});

Categories