I have tried manipulating the code used by Ke Yang where localStorage is used to mirror text in form fields across to other fields. I want to do something similar.
I have one page (a library of downloadables) which contains about 10 lead-generation forms on it. Once filled out and submitted, the form sends the user the downloadable. Simple stuff. But say the user wants to download more than one thing on this page, it doesn't make sense to have them keep filling out the same forms. The forms are exactly the same, same fields and field-names, just different form IDs.
I want to use localStorage so that once a user has filled out one form on the page, they can check a box at the top of any of the other forms and the browser will autofill their data, then they hit submit. Ideally, this data is saved even after they leave the page. Data submission is handled by the form itself, so there's no need for cookies (and localStorage is better).
Here's the (minimalised) code I have so far, which goes under the (function($) { in my scripts.js file:
$( ‘input[name=target]’ ).click(function() {if($(‘input[name=target]’).is(‘:checked’)) {
if (localStorage[“first-name”]) {
$(‘input[name=first-name]’).val(localStorage[“first-name”]);
}
if (localStorage[“last-name”]) {
$(‘input[name=last-name]’).val(localStorage[“last-name”]);
}
if (localStorage[“your-email”]) {
$(‘input[name=your-email]’).val(localStorage[“your-email”]);
}
}
});$(‘.wpcf7-text’).change(function () {
localStorage[$(this).attr(‘name’)] = $(this).val();
});
Above you see the names of the different fields within one form. The HTML looks like this, where the checkbox would need to be ticked to call the stored form data:
<p><input id="target2" name="target2" type="checkbox" value="Downloaded our stuff before?" /> Downloaded our stuff before?</p>
<input type = "text" name ="first-name" class="wpcf7-text">
<input type = "text" name ="last-name" class="wpcf7-text">
<input type = "text" name ="your-email" class="wpcf7-text">
The text previously entered into a form will need to be stored (not cleared) after a user hits submit, allowing them to download more stuff easily after their first download.
Thanks heaps in advance!
It seems to me that there are too many issues in your code
1) $( ‘input[name=target]’ ) . This should be $("input[name='target']") .Check this link for more.
2) Use setItem to set the items
3) You need to use .on to delegate the change
I have to rewrite the html to make this work. Just for demo I used only three input field
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" crossorigin="anonymous"></script>
</head>
<body>
<p><input id="target" name="target" type="checkbox" value="Downloaded our stuff before?" /> Downloaded our stuff before?</p>
<input type = "text" name ="first-name" class="wpcf7-text">
<input type = "text" name ="last-name" class="wpcf7-text">
<input type = "text" name ="your-email" class="wpcf7-text">
<script>
$("#target").change(function(){
if($(this).is(":checked")) {
if (localStorage['first-name']) {
$("input[name='first-name']").val(localStorage['first-name']);
}
if (localStorage['last-name']) {
$("input[name='last-name']").val(localStorage['last-name']);
}
if (localStorage['your-email']) {
$("input[name='your-email']").val(localStorage['your-email']);
}
}
});
$(".wpcf7-text").on("change",function () {
localStorage.setItem($(this).attr("name") , $(this).val());
});
</script>
</body>
</html>
Before applying below solution make sure you have given id to your form and your all form controls will have name and id, name and id of control should be identical.
call bellow function before submmiting form
function beforeSubmmit(){
localStorage["YourFormID"] = JSON.stringify($('#YourFormID').serializeArray());
}
on load of page call bellow function
function onLoad(){
if (loadFromLocal == true){
var fromFileds = JSON.parse(localStorage["YourFormID"])
for(var formfiled in fromFileds)
{
$("#"+formfiled.name).val(formfiled.value);
}
}
}
and one more thing
$('#YourFormID').serializeArray()
this function returns array objects , and each object is having two keys name & value, name is name of form control and value contains value of the control.
Just store this array in local storage and retrieve on load and set if by for loop, no need to do hard coding.
$("form").length
this will give you total forms count
$("form")[0].id
and this will give you id of form, you can put for loop and store all forms in local storage
Related
I am attempting to create a couple of web pages that will allow me to fill out a form on input.html and have the entered data appended to a different HTML file, index.html.
I have been searching for an answer for a couple of hours now and it might just drive me insane!
Here is some example code of what I'm trying to do:
HTML form input.hmtl:
<form>
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Javascript to get entered data and pass to index.html:
var userInput = document.querySelector("#userinput");
var submit = document.querySelector("#submit");
function addToIndex()
{
// create new element on index.html
}
submit.addEventListener("click", addToIndex, false);
HTML output file index.html:
<div id="contentstart">
<!-- newly created element here -->
</div>
I have attempted using this solution, but Chrome's console gives me an error and tells me that newWindow is not a function. I just stumbled upon using the <iframe> element in a couple of answers but don't quite understand it yet (I'm a noob).
Thanks in advance!
The best option is to use a web server or a serverless implementation. Server code can be written in multiple languages. Some of the languages include PHP, NodeJS, and ASP.NET.
However, you can pass data using browser storage.
But, browser storage is not secure and can be wiped at any time by the user. If you are storing information such as passwords or data that should be visible to multiple users, you should use a web server and/or database.
You need to have a script on both pages. The page with the form will store/set the data. The index page will retrieve the data and use javascript to render more content.
function addToIndex()
{
localStorage.setItem('input', userInput .value)
}
The script for the index page would look something like this.
var data = localStorage.getItem('input');
if (input) {
document.querySelector('#contentstart').innerHTML = data;
}
I put together a simple demo here.
http://plnkr.co/edit/iAitGxtdsHwXowNg
For you to receive data from a form in a different file, you will need a server-side language like php.
So the form will have this structure
<form action="external_file.php" method="get">
<label>
Enter something:
<input type="text" id="userinput" name="user_input" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Note the action="external_file.php and the name="user_input" attribute added to the input element.
Then the file: external_file.php might have the following structure to receive the content from the form
<?php
$input = $_GET["user_input"];
//do something with $input
echo 'The data you entered is: ' . $input;
?>
I showed you the way to start. The rest is up to you, you can do whatever you want to do. I hope you could help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id ="form">
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
<script>
let form = document.getElementById("form");
let userInput = document.getElementById("userinput");
form.addEventListener("submit", submitForm) //this function will work when the form is submit
function submitForm (e) {
e.preventDefault() // this event will prevent page refresh when form submit
let userInputValue = userInput.value; // userinput value
console.log(userInputValue);
moveToAnotherPage(userInputValue); //we send the value we get from userinput to use in another function.
}
function moveToAnotherPage (value) {
// Select the index2 html elements and add with innerhtml or something.
//to do this, you may need to save the userinput value you received to localStorage and pull it from it. I suggest you look into localStorage .And if you know php, you can use it.
}
</script>
</body>
</html>
We want get selected value of radio button after refreshing page. We have two radio button like Online & Offline. If I select Online and then after refreshing page at that time I want selected value of radio button back.
You can use following things :-
1) localStorage -HTML5
2) cookies ..
I would recommend using localStorage
before refreshing page set local storage:-
localStorage.setItem('radioBtnId',valSelected);
//valSelected is the selected value of radiobutton.
and after refreshing page, do
var val=localStorage.getItem('radioBtnId');
and use val to default select the radioButton.
Also delete the localstorage value because you don't need it any more as:
localStorage.removeItem('radioBtnId');
Adding code as given in the comment
<html>
<head>
<script>
function setDefaultValue(id)
{
localStorage.setItem('status',id);
}
function getDefaultValue()
{
var valId=localStorage.getItem('status');
document.getElementById("valId").checked = true;
localStorage.removeItem('status');
}
</script>
<title>
</title>
</head>
<body>
<form>
<input id="statusOnline" type="radio" value="Online" onchange="setDefaultValue('statusOnline');">
<input id="statusOffline" type="radio" value="Offline" onchange="setDefaultValue('statusOffline');">
</form>
</body>
</html>
haven't tested this code .. just giving you the Idea how it will be used . Hope it helps ...
Use Local storage.
localStorage.setItem('some key',radiobuttonValue); //To set values
localStorage.getItem('some key'); // To get values
These values will be stored on your browsers storage. Note that this doesnt work if user clears the cache.
I'm using jQuery's autocomplete() method on a text field with Object.getOwnPropertyNames(projects) as the source:
$(function() {
$("#project").autocomplete({source: Object.getOwnPropertyNames(projects)});
}
The Object.getOwnPropertyNames(projects) method returns an array of the projects object's property names.
This works just fine. However:
If the user enters a new value in the field (ie, a value that is not already a property of the projects object), then the value gets added as a property when a button is clicked (the page is not reloaded). Button click also resets the field. When I try entering a value in the field now, the suggestions list doesn't show the newly added property (unless I call the autocomplete method again). How do I resolve this?
Psst. If I assign the value of Object.getOwnPropertyNames(projects) to an array, use the array as the source in the autocomplete method and update the array on button click, then the suggestions list shows the newly added value.
The following function handles the button click:
$("#clock").click(function() {
if (!($("#project").val() in projects)) { //If value is not already a property
projects[$("#project").val()] = $("#skill").val(); //skill is another field
}
$('#theForm')[0].reset(); //theForm is the id of the form that contains the fields
}
Try updating the source option of the autocomplete after the localArr is updated:
$("#project").autocomplete("option", "source", localArr);
After the form is submitted, your page refreshes, so the javascript code runs again, and what your javascript code says is to auto-complete the input field with the elements from the given source. You have to make sure your source now includes the new project the user just added.
PHP example:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script type="text/javascript">
var projects;
jQuery(function() {
projects = {project1: 1, project2: 2, project3: 3, project4: 4};
<?php if (isset($_GET['project'])): ?>
projects['<?php echo $_GET['project']?>'] = 'foobar';
<?php endif ?>
jQuery("[name=project]").autocomplete({source: Object.getOwnPropertyNames(projects)});
});
</script>
</head>
<body>
<form action="">
Project: <input type="text" name="project" value="<?php echo isset($_GET['project']) ? $_GET['project'] : ""?>"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
As #mimarcel pointed out, $("#project").autocomplete({source: Object.getOwnPropertyNames(projects)}); only created an array that wouldn't change when I updated the projects object. In order for the suggestions list to reflect changes on the object, I had to use a callback, like so:
$('#project').autocomplete({
source: function(request, response){
response(Object.getOwnPropertyNames(projects));
}
});
Is it possible to have an html that links to different websites depending on what text the user enters? In other words, I have a simple text form where users can enter text and then hit submit. As an example of what I'm hoping to do, is there a way to set it up so that if they enter "ABC" and hit submit it takes them to google, but if they enter "XYZ" it takes them to yahoo?
Yes you can, but you need JavaScript, here's a very contrived example almost reminiscent of Web 1.0 scripts. The code sets up a listener on the textfield (keyup), and whenever it changes it calls the function changed, which then evaluates the value in the field. If it matches 'XYZ', it then sets the form's action property to be the URL where you want the form submission. In this particular case, the URL to will be something that doesn't exist. Now of course this is not a complete solution and you'll have to spend a bit of time getting the handler to work correctly.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form id="myform">
<input type="text" id="mytext" onkeyup="changed()">
</form>
<script type="text/javascript">
function changed()
{
var v = document.getElementById('mytext').value;
if("XYZ" === v)
{
var action = "http://www.foobar.nothing/" + v;
document.getElementById('myform').action = action;
}
}
</script>
</body>
</html>
I need to validate my form fields displayed in facebox.
The problem is that i am unable to get the values of the fields by using javascript.
for ex: document.form.field_name.value doesnt return its value.
Code sample :
<script type="text/javascript">
function validate()
{
if (document.form1.field.value=='')
{
alert ("Field cannot be left blank");
}
}
</script>
<form name="form1" onsubmit="return validate()">
<input type="text" name="field" />
</form>
A way to do this would be to pass the value directly from the form to the validation code.
<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" />
</form>
Or you could even use a text box without the form using:
<input type="text" id="field"
onkeydown="if (event.keyCode == 13) return validate(this.value)" />
Update the script to allow for the new value parameter:
<script type="text/javascript">
function validate(val) {
if (val.length < 1)
{
alert ("field cannot be left blank");
return false; //to stop the default action of submitting the form
} else {
alert ("Value: "+val);
return true; //allow to submit the page
}
}
</script>
This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.
I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.
NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.
Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...
This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.