Details - First Visit this link - http://www.flacement.com/jobssearch/iffco-tokio-job-in-jharsuguda/
its created by WP and Plugin is Jobs for Wordpress by Blueglass
what i want -- when someone click apply , some one can apply via flacement ID but i want to validate that ID from sheetsu JS API and Insert that code in backend code.
what i need you to help me
here is sheetsu api code
<head>
<script src="//script.sheetsu.com/"></script>
</head>
<body>
<script>
function successFunc(data) {
console.log(data);
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: active,
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
</script>
</body>
when some one write flacement ID ( 3894-8873-7149) its search from sheestu API
if value= active then proceed else , alert > your are block.
if value= not found then , alert > register here
please make me a JS validation script with HTML
Try this one
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\nchecking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\nid found");
}
else{
document.body.append('\nid not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
}
else {
document.body.append('\ninvalid id');
}
}
<input id="input-text_flacement-id">
<script src="https://script.sheetsu.com/"></script>
NOTE: try not using this is_focused technique
Related
I am trying to add a JS script file called chatfunction.js into my index.html in Blazor but it gives me an error that it cannot find a file. My CSS is linked correctly and the HTML and CSS both show up but it does not provide any of the JS functionality that I have implemented.
I am adding it at the bottom of my HTML in index.html like this:
....
<script src="_framework/blazor.webassembly.js"></script>
<script src="chatfunction.js"></script>
</body>
</html>
Here is my project structure
Now when I try compiling it gives me this error:
(JS) File 'C:/Users/darka/source/repos/chatproject/wwwroot/js/mysrc.js' not found.
I don't get why it can't find it and I am confused as to why it thinks my file is mysrc.js as there is no file like that in my project structure.
Any pointers how to fix this?
Here is the layout of my JS file
var botController = (function () {
})();
var uiController = (function () {
})();
var controller = (function (botCntr, uiCntr) {
var $chatCircle,
$chatBox,
$chatBoxClose,
$chatBoxWelcome,
$chatWraper,
$submitBtn,
$chatInput,
$msg;
/*toggle*/
function hideCircle(evt) {
evt.preventDefault();
$chatCircle.hide('scale');
$chatBox.show('scale');
$chatBoxWelcome.show('scale');
}
function chatBoxCl(evt) {
evt.preventDefault();
$chatCircle.show('scale');
$chatBox.hide('scale');
$chatBoxWelcome.hide('scale');
$chatWraper.hide('scale');
}
function chatOpenMessage(evt) {
evt.preventDefault();
$chatBoxWelcome.hide();
$chatWraper.show();
}
//generate messages on submit click
function submitMsg(evt) {
evt.preventDefault();
//1. get input message data
msg = $chatSubmitBtn.val();
//2.if there is no string button send shoudn't work
if (msg.trim() == '') {
return false;
}
//3. add message to bot controller
callbot(msg);
//4. display message to ui controller
generate_message(msg, 'self');
}
function chatSbmBtn(evt) {
if (evt.keyCode === 13 || evt.which === 13) {
console.log("btn pushed");
}
}
/* var input = uiCntr.getInput();*/
/* $chatSubmitBtn.on("click", hideCircle);*/
function init() {
$chatCircle = $("#chat-circle");
$chatBox = $(".chat-box");
$chatBoxClose = $(".chat-box-toggle");
$chatBoxWelcome = $(".chat-box-welcome__header");
$chatWraper = $("#chat-box__wraper");
$chatInput = $("#chat-input__text");
$submitBtn = $("#chat-submit");
//1. call toggle
$chatCircle.on("click", hideCircle);
$chatBoxClose.on("click", chatBoxCl);
$chatInput.on("click", chatOpenMessage);
//2. call wait message from CRM-human
$submitBtn.on("click", chatSbmBtn);
$chatInput.on("keypress", chatSbmBtn);
//6. get message from bot controller-back end
//7. display bot message to ui controller
}
return {
init: init
};
})(botController, uiController);
$('.chat-input__form').on('submit', function (e) {
e.preventDefault();
msg = $('.chat-input__text').val();
$('.chat-logs').append('<div id="cm-msg-0" class="chat-msg background-warning push-right bot"><div class="cm-msg-text">' + msg + '</div><span class="msg-avatar"><img class="chat-box-overlay_robot" src="https://www.meetsource.com//userStyles/images/user.png"></span></div>');
$('.chat-input__text').val('');
});
$(document).ready(controller.init);
function talk() {
var user = document.getElementById("userBox").value;
document.getElementById("userBox").value = "";
document.getElementById("chatLog").innerHTML += user + "<br>";
}
I think your script line needs to be:
<script src="js/chatfunction.js"></script>
I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')
I'm a little worried and in a hurry and I'm not sure if this is the right place to ask this, but I literally have no idea where else to ask.
Long story short, I wanted to clear my gmail account from spam and found the following link while searching for a way to do this:
https://www.labnol.org/internet/gmail-unsubscribe/28806/
Like a complete idiot, I followed the instructions blindly without suspecting anything. After completing the steps, nothing really happened (the spreadsheet wasn't filling) so I stopped the script and removed it from my google accounts permissions and started inspecting the code that was used. It consists of three files, the google script:
function getConfig() {
var params = {
label:doProperty_("LABEL") || "Unsubscribe"
};
return params;
}
function config_() {
var html = HtmlService.createHtmlOutputFromFile('config')
.setTitle("Gmail Unsubscriber")
.setWidth(300).setHeight(200).setSandboxMode(HtmlService.SandboxMode.IFRAME);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function help_() {
var html = HtmlService.createHtmlOutputFromFile('help')
.setTitle("Google Scripts Support")
.setWidth(350).setHeight(120);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function createLabel_(name) {
var label = GmailApp.getUserLabelByName(name);
if (!label) {
label = GmailApp.createLabel(name);
}
return label;
}
function log_(status, subject, view, from, link) {
var ss = SpreadsheetApp.getActive();
ss.getActiveSheet().appendRow([status, subject, view, from, link]);
}
function init_() {
Browser.msgBox("The Unsubscriber was initialized. Please select the Start option from the Gmail menu to activate.");
return;
}
function onOpen() {
var menu = [
{name: "Configure", functionName: "config_"},
null,
{name: "☎ Help & Support",functionName: "help_"},
{name: "✖ Stop (Uninstall)", functionName: "stop_"},
null
];
SpreadsheetApp.getActiveSpreadsheet().addMenu("➪ Gmail Unsubscriber", menu);
}
function stop_(e) {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
if (!e) {
Browser.msgBox("The Gmail Unsubscriber has been disabled. You can restart it anytime later.");
}
}
function doProperty_(key, value) {
var properties = PropertiesService.getUserProperties();
if (value) {
properties.setProperty(key, value);
} else {
return properties.getProperty(key);
}
}
function doGmail() {
try {
var label = doProperty_("LABEL") || "Unsubscribe";
var threads = GmailApp.search("label:" + label);
var gmail = createLabel_(label);
var url, urls, message, raw, body, formula, status;
var hyperlink = '=HYPERLINK("#LINK#", "View")';
var hrefs = new RegExp(/<a[^>]*href=["'](https?:\/\/[^"']+)["'][^>]*>(.*?)<\/a>/gi);
for (var t in threads) {
url = "";
status = "Could not unsubscribe";
message = threads[t].getMessages()[0];
threads[t].removeLabel(gmail);
raw = message.getRawContent();
urls = raw.match(/^list\-unsubscribe:(.|\r\n\s)+<(https?:\/\/[^>]+)>/im);
if (urls) {
url = urls[2];
status = "Unsubscribed via header";
} else {
body = message.getBody().replace(/\s/g, "");
while ( (url === "") && (urls = hrefs.exec(body)) ) {
if (urls[1].match(/unsubscribe|optout|opt\-out|remove/i) || urls[2].match(/unsubscribe|optout|opt\-out|remove/i)) {
url = urls[1];
status = "Unsubscribed via link";
}
}
}
if (url === "") {
urls = raw.match(/^list\-unsubscribe:(.|\r\n\s)+<mailto:([^>]+)>/im);
if (urls) {
url = parseEmail_(urls[2]);
var subject = "Unsubscribe";
GmailApp.sendEmail(url, subject, subject);
status = "Unsubscribed via email";
}
}
if (status.match(/unsubscribed/i)) {
UrlFetchApp.fetch(url, {muteHttpExceptions: true});
}
formula = hyperlink.replace("#LINK", threads[t].getPermalink());
log_( status, message.getSubject(), formula, message.getFrom(), url );
}
} catch (e) {Logger.log(e.toString())}
}
function saveConfig(params) {
try {
doProperty_("LABEL", params.label);
stop_(true);
ScriptApp.newTrigger('doGmail')
.timeBased().everyMinutes(15).create();
return "The Gmail unsubscriber is now active. You can apply the Gmail label " + params.label + " to any email and you'll be unsubscribed in 15 minutes. Please close this window.";
} catch (e) {
return "ERROR: " + e.toString();
}
}
function parseEmail_(email) {
var result = email.trim().split("?");
return result[0];
}
And two other .html files called config.html:
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script>
function closeWindow() {
google.script.host.close();
}
function showError(error) {
document.getElementById("error").innerHTML = error;
}
function showConfig(params) {
if (params.label !== "")
document.getElementById("label").value = params.label;
return;
}
function validate() {
var label = document.getElementById("label").value;
if (label.trim() === "") {
showError("Please enter a Gmail label name..");
return;
} else {
showError("Saving configuration, please wait..");
var params = {
label: label
};
google.script.run.withSuccessHandler(showError).saveConfig(params);
}
}
</script>
<form>
<div class="form-group block">
<p style="margin-bottom:4px;">Enter Gmail Label Name:</p>
<input type="text" id="label" name="label" placeholder="Your email address.." style="width: 250px;" />
</div>
<p>
<input class="blue" type="button" value="Save configuration" onclick="validate()" />
<input class="green" type="button" value="Close window" onclick="google.script.host.close()" />
</p>
<p class="error" id="error"></p>
</form>
<script>
google.script.run.withSuccessHandler(showConfig).getConfig();
</script>
And lastly help.html:
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<base target="_blank">
</head>
<div class="block">
<p>If you are need help with the program, please refer to the online tutorial. For support and customization, please submit your requirements at <strong>ctrlq.org</strong>.</p>
</div>
<div class="block">
<a class="button blue" href="mailto:amit#labnol.org" style="width:120px;">amit#labnol.org</a>
<a class="button green" href="https://twitter.com/labnol" style="width:120px;margin-right:10px">Tweet #labnol</a>
<input class="red" type="button" value="Close" onclick="google.script.host.close()" />
</div>
Is there any way that my account could be in any danger?
I am the author of this Google Script and it is completely safe. In fact, you have access to the full source code so you know exactly what it is doing.
Also, if you like to remove any Google Script from your account, here's how:
Go to https://security.google.com/settings/security/permissions
Click the script you wish to uninstall
Next click Remove and you are done.
I am having a problem with the following javascript/ajax code. The code searches a JSON file which just has some contact names and email addresses in it. When the "keyup" event calls addr.search everything is fine and in the function call to ajaxCall the attributes request.readyState=4 and request.Status=200, but when the "submit" event calls the same search calling the same addr.search function the request.status is 0 and it fails.
Is it possible it has something to do with the action attribute in the form element?
I should add that I am running this on a WAMP server.
/* standard Ajax xhr function */
function getHTTPObject() {
var xhr;
if (window.XMLHttpRequest) { // check for support
// if it's supported, use it
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // check for the IE 6 Ajax
// save it to the xhr variable
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
// spit out the correct one so we can use it
return xhr;
}
/* define the Ajax call */
function ajaxCall(dataUrl, outputElement, callback) {
/* use our function to get the correct Ajax object based on support */
var request = getHTTPObject();
outputElement.innerHTML = "Loading";
request.onreadystatechange = function() {
// check to see if the Ajax call went through
if ( request.readyState === 4 && request.status === 200 ) {
// save the ajax response to a variable
var contacts = JSON.parse(request.responseText);
// make sure the callback is indeed a function before executing it
if(typeof callback === "function"){
callback(contacts);
} // end check
} // end ajax status check
} // end onreadystatechange
request.open("GET", dataUrl, true);
request.send(null);
}
/* wrap everything in an anonymous function to contain the variables */
(function(){
/* define the DOM elements and common variables you'll need */
var searchForm = document.getElementById("search-form"),
searchField = document.getElementById("q"),
getAllButton = document.getElementById("get-all"),
target = document.getElementById("output");
/* define address book methods */
var addr = {
search : function(event){
// set the output element
var output = document.getElementById("output");
ajaxCall('data/contacts.json', output, function (data) {
// save the input value, contacts length and i to variables
var searchValue = searchField.value,
addrBook = data.addressBook,
count = addrBook.length,
i;
// stop the default behavior
event.preventDefault();
// clear the target area just incase there's something in it.
target.innerHTML = "";
// check the count, of course
if(count > 0 && searchValue !== ""){
// loop through the contacts
for(i = 0; i < count; i = i + 1) {
// look through the name value to see if it contains the searchterm string
var obj = addrBook[i],
isItFound = obj.name.indexOf(searchValue);
// anything other than -1 means we found a match
if(isItFound !== -1) {
target.innerHTML += '<p>' + obj.name + ', '+ obj.email +'<p>';
} // end if
} // end for loop
} // end count check
}); // end ajax call
},
getAllContacts : function () {
// set the output element
var output = document.getElementById("output");
// start Ajax call
ajaxCall('data/contacts.json', output, function (data) {
var addrBook = data.addressBook,
count = addrBook.length,
i;
// clear the target area just incase there's something in it.
target.innerHTML = "";
// check the count, of course
if(count > 0) {
// loop through the contacts
for(i = 0; i < count; i = i + 1) {
// look through the name value to see if it contains the searchterm string
var obj = addrBook[i];
target.innerHTML += '<p>' + obj.name + ', '+ obj.email +'<p>';
} // end for loop
} // end count check
}); // end ajax call
},
setActiveSection : function() {
// add a class of "active" the wrapping div
this.parentNode.setAttribute("class", "active");
},
removeActiveSection : function() {
// remove the class from the wrapping div
this.parentNode.removeAttribute("class");
},
addHoverClass : function() {
// remove the class from the wrapping div
searchForm.setAttribute("class", "hovering");
},
removeHoverClass : function(){
// remove the class from the wrapping div
searchForm.removeAttribute("class");
}
} // end addr object
// activate auto complete on keyUp
searchField.addEventListener("keyup", addr.search, false);
// set active section on focus of the form field
searchField.addEventListener("focus", addr.setActiveSection, false);
// remove active section on blur of the form field
searchField.addEventListener("blur", addr.removeActiveSection, false);
// get all contacts when you click the button
getAllButton.addEventListener("click", addr.getAllContacts, false);
// add hover class on mouse over of the form field
searchForm.addEventListener("mouseover", addr.addHoverClass, false);
// remove hover class on mouse out of the form field
searchForm.addEventListener("mouseout", addr.removeHoverClass, false);
// activate search on form submit
searchForm.addEventListener("submit", addr.search, false);
})(); // end anonymous function
Here is the html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Address Book Application</title>
<style>
.active { background:#ddd; }
.hovering { background:#eee; }
form > div { padding:10px; }
</style>
</head>
<body>
<h1>Address Book</h1>
<form action="" method="get" id="search-form">
<div>
<label for="q">Search address book</label>
<input type="search" id="q" name="q" required placeholder="type a name" autocomplete="off">
</div>
<div class="button-group">
<button type="submit" id="search-btn">search</button>
<button type="button" id="get-all">get all contacts</button>
</div><!--/.button-group-->
</form>
<div id="output" aria-atomic="true" aria-live="polite"></div><!--/#output-->
<script src="js/addressbook.js"></script>
</body>
</html>
and the JSON file:
{
"addressBook" : [
{
"name": "hillisha",
"email": "hill#example.com"
},
{
"name": "paul",
"email": "cleveland#example.com"
},
{
"name": "vishaal",
"email": "vish#example.com"
},
{
"name": "mike",
"email": "grady#example.com"
},
{
"name": "jamie",
"email": "dusted#example.com"
},
{
"name": "gini",
"email": "g#example.com"
},
{
"name": "kristen",
"email": "marv#example.com"
},
{
"name": "starlen",
"email": "stars#example.com"
},
{
"name": "archie",
"email": "ie#example.com"
},
{
"name": "bill",
"email": "hickey#example.com"
}
]
}
You're not stopping the default action. It doesn't matter for the keyup event, but the form does get submitted (with an action="" to the same location so you're not really noticing it). On leaving the page, the runnning ajax requests get aborted and you see the status code 0.
The problem is that you're invoking event.preventDefault(); from the ajax callback - it's too late then, all event-related actions have already been run. Move it to the first line of your addr.search function.
My scenario: I have an application that is 9 pages long for a total of about 125 inputs of varying types and sizes (only input, textarea, radio, and selects). I'd like to use local storage to save the form values. The user can move between the pages (e.g. to review before submitting the application) so I don't want to clear the local storage until they submit the application and if they change from page to page, the form should reload its values from local storage. Once they submit the form, then I'll clear the local storage but until then, the local storage should be retained.
I found this great jquery plugin and a demo page which appears to almost do what I'm looking for - well, with two exceptions:
1) The plugin prompts the user if they want to restore their previously entered info which I'd prefer to not have (I'd rather have the data just be there). My navigational buttons at the bottom of the form are simply "Previous" and "Continue" (on the first page, it is just "Continue" and on the last page they would be "Previous" and "Submit Application").
2) The plugin will prompt the user even if there is no data to load (this would be a non-issue if I can just have it load data if there is any and skip it if there is not). For example, the very first visit to the page will prompt the user to restore previously entered data.
Here is a link to the jquery.remember-state.js used in the demo page.
=======================================================
I took the demo above and tweaked the jquery.remember-state.js to try and make it do what I need but it isn't working correctly.
Here is my (jsFiddle).
NOTE 1: the jsFiddle is meant to just show my code and is not a necessarily a working example in the jsFiddle environment. If you copy the code to your local environment, you should be able to access the console.log to see if/what gets saved to the localStorage.
NOTE 2: S.O. wants formatted code inline so I'll see what I can do to make it format correctly.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>LocalStorage and Unload State Save</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../jQueryPlugins/RememberState/form.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!-- use the modified jquery.remember-state.js code in the JavaScript panel instead
the script tag below is the original js file
<script src="http://shaneriley.com/jquery/remember_state/jquery.remember-state.js"></script>-->
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
(function($) {
/* jQuery form remember state plugin
Name: rememberState
Version: 1.3
Description: When called on a form element, localStorage is used to
remember the values that have been input up to the point of either
saving or unloading. (closing window, navigating away, etc.) If
localStorage isn't available, nothing is bound or stored.
The plugin looks for an element with a class of remember_state to show
a note indicating there is stored data that can be repopulated by clicking
on the anchor within the remember_state container. If the element doesn't
exist, it is created and prepended to the form.
Usage: $("form").rememberState("my_object_name");
Notes: To trigger the deletion of a form's localStorage object from
outside the plugin, trigger the reset_state event on the form element
by using $("form").trigger("reset_state");
*/
if (!window.localStorage || !window.JSON) {
if (console && console.log) {
!window.localStorage && console.log("ERROR: you browser does not support" +
" localStorage (use this polyfill https://gist.github.com/350433)");
!window.JSON&& console.log("ERROR: you browser does not support" +
" JSON (use this polyfill http://bestiejs.github.com/json3/)");
}
return $.fn.rememberState = function() { return this; };
}
var remember_state = {
name: "rememberState",
clearOnSubmit: false, //default was true;
// ****************************
/*noticeDialog: (function() {
return $("<p />", {"class": "remember_state"})
.html('Do you want to restore your previously entered info?');
})(),*/
// ****************************
ignore: null,
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
clickNotice: function(e) {
var data = JSON.parse(localStorage.getItem(e.data.instance.objName)),
$f = $(this).closest("form"),
$e;
for (var i in data) {
$e = $f.find("[name=\"" + data[i].name + "\"]");
if ($e.is(":radio, :checkbox")) {
$e.filter("[value=" + data[i].value + "]").prop("checked", true);
}
else if ($e.is("select")) {
$e.find("[value=" + data[i].value + "]").prop("selected", true);
}
else {
$e.val(data[i].value);
}
$e.change();
}
e.data.instance.noticeDialog.remove();
e.preventDefault();
},
chooseStorageProp: function() {
if (this.$el.length > 1) {
if (console && console.warn) {
console.warn("WARNING: Cannot process more than one form with the same" +
" object. Attempting to use form IDs instead.");
}
this.objName = this.$el.attr("id");
}
},
errorNoID: function() {
if (console && console.log) {
console.log("ERROR: No form ID or object name. Add an ID or pass" +
" in an object name");
}
},
saveState: function(e) {
var instance = e.data.instance;
var values = instance.$el.serializeArray();
// jQuery doesn't currently support datetime-local inputs despite a
// comment by dmethvin stating the contrary:
// http://bugs.jquery.com/ticket/5667
// Manually storing input type until jQuery is patched
instance.$el.find("input[type='datetime-local']").each(function() {
var $i = $(this);
values.push({ name: $i.attr("name"), value: $i.val() });
});
values = instance.removeIgnored(values);
values.length && internals.setObject(instance.objName, values);
},
save: function() {
var instance = this;
if (!this.saveState) {
instance = this.data(remember_state.name);
}
instance.saveState({ data: { instance: instance } });
},
removeIgnored: function(values) {
if (!this.ignore) { return values; }
$.each(this.ignore, function(i, name) {
$.each(values, function(j, input) {
if (name === input.name) { delete values[j]; }
});
});
return values;
},
init: function() {
var instance = this;
// ****************************
/* if (instance.noticeDialog.length && instance.noticeDialog.jquery) {
instance.noticeDialog.find("a").bind("click." + instance.name, {
instance: instance
}, instance.clickNotice);
}*/
// ****************************
instance.chooseStorageProp();
if (!instance.objName) {
instance.errorNoID();
return;
}
if (localStorage[instance.objName]) {
// ****************************
/*if (instance.noticeDialog.length && typeof instance.noticeDialog === "object") {
instance.noticeDialog.prependTo(instance.$el);
}
else {
instance.$el.find(instance.noticeSelector).show();
}*/
// ****************************
}
if (instance.clearOnSubmit) {
instance.$el.bind("submit." + instance.name, function() {
instance.$el.trigger("reset_state");
$(window).unbind("unload." + instance.name);
});
}
instance.$el.bind("reset_state." + instance.name, function() {
localStorage.removeItem(instance.objName);
});
// ****************************
/*$(window).bind("unload." + instance.name, { instance: instance }, instance.saveState);
instance.$el.find(":reset").bind("click.remember_state", function() {
$(this).closest("form").trigger("reset_state");
});*/
}
};
var internals = {
setObject: function(key, value) { localStorage[key] = JSON.stringify(value); },
getObject: function(key) { return JSON.parse(localStorage[key]); },
createPlugin: function(plugin) {
$.fn[plugin.name] = function(opts) {
var $els = this,
method = $.isPlainObject(opts) || !opts ? "" : opts;
if (method && plugin[method]) {
plugin[method].apply($els, Array.prototype.slice.call(arguments, 1));
}
else if (!method) {
$els.each(function(i) {
var plugin_instance = $.extend(true, {
$el: $els.eq(i)
}, plugin, opts);
$els.eq(i).data(plugin.name, plugin_instance);
plugin_instance.init();
});
}
else {
$.error('Method ' + method + ' does not exist on jQuery.' + plugin.name);
}
return $els;
};
}
};
internals.createPlugin(remember_state);
})(jQuery);
});//]]>
</script>
<script>
var thisPage = 'page1'; //defines the variable to use for local storage
$(function() {
$("form")
.rememberState({objName: thisPage})
.submit(function() {localStorage.setItem(thisPage, $(this).serializeArray());
return true;
});
});
</script>
</head>
<body>
<form method="post" action="page2.cfm">
<fieldset>
<dl>
<dt><label for="first_name">First Name</label></dt>
<dd><input type="text" name="first_name" id="first_name" /></dd>
<dt><label for="last_name">Last Name</label></dt>
<dd><input type="text" name="last_name" id="last_name" /></dd>
</dl>
</fieldset>
<fieldset class="actions">
<input type="submit" value="Continue" />
</fieldset>
</form>
</body>
</html>
I thought this was going to be tougher than it was. Here is the solution I came up with:
On the form page when the submit button is pressed:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var thisPageID = 'page1'; // each page gets its own
$('form').submit(function() {
var formFields = $(this).serialize();
localStorage.setItem(thisPageID, formFields);
data = localStorage.getItem(thisPageID);
return true;
});
});
</script>
Then on the final page, I retrieve the data for each page by its page id from the local storage and populate my div tags with the data.
function getLocalData(id){
var ApplicantData;
ApplicantData = localStorage.getItem(id);
if (ApplicantData){
$.each(ApplicantData.split('&'), function (index, elem) {
var vals = elem.split('=');
var $div = $("#"+vals[0]);
var separator = '';
// console.log($div);
if ($div.html().length > 0) {
separator = ', ';
}
$div.html($div.html() + separator + decodeURIComponent(vals[1].replace(/\+/g, ' ')));
});
}
}
Some of the Articles that helped me (some SO, some external):
- Clear localStorage
- http://www.simonbingham.me.uk/index.cfm/main/post/uuid/using-html5-local-storage-and-jquery-to-persist-form-data-47
- http://www.thomashardy.me.uk/using-html5-localstorage-on-a-form
There were more but this is all I still had open in tabs.