How can I save javascript variables locally? - javascript

I am a beginner in Javascript/Jquery and I am making a mobile web app using jquery mobile and jquery and I can't figure out how to display all my inputs in one place. No matter how many data I enter into the form it always displays the last entered .Please, any help?
$(document).ready(function() {
if(localStorage['linrval'],localStorage['linrdate']){
$('#inrhist').prepend('<div class="inrval">'+localStorage['linrdate']+ ' ---- ' +localStorage['linrval']+ '</div>');
};
$('#inrbtn').click(function(){
var inrval=$('input[name=user]').val();
var inrdate=$('input[name=dateinr]').val();
localStorage.setItem('linrval',inrval);
localStorage.setItem('linrdate',inrdate);
$('#inrhist').prepend('<div class="inrval">'+inrdate+ ' ---- ' +inrval+ '</div>');
});

Couple of things need to change here every time you need to add into array instead of you update the item value with same property. localStorage only supports strings.
$(document).ready(function() {
//localStorage.removeItem("users");
var userStr = localStorage.getItem('users');
if (userStr != null && userStr != undefined) {
var jsonObj = JSON.parse(userStr);
console.log("onload value", jsonObj);
$.each(jsonObj.items, function(i, item) {
$('#inrhist').prepend('<div class="inrval">'+item.user +'--'+item.dateinr+'</div>');
});
}
$('#inrbtn').click(function () {
var dataItems = { items: [] };
var inrval = $('input[name=user]').val();
var inrdate = $('input[name=dateinr]').val();
var item = { user: inrval, dateinr: inrdate };
var usersList = localStorage.getItem('users');
var jsonObj;
if (usersList == null) {
dataItems.items.push(item);
jsonObj = JSON.parse(JSON.stringify(dataItems));
}
else {
jsonObj = JSON.parse(usersList);
jsonObj.items.push(item);
}
jsonStr = JSON.stringify(jsonObj);
console.log(jsonStr);
localStorage.setItem("users", jsonStr);
$('#inrhist').prepend('<div class="inrval">' + inrdate + '--' + inrval + '</div>');
});
});
LIVE DEMO

You have this:
if(localStorage['linrval'],localStorage['linrdate']){...}
Such expression is true if and only if localStorage['linrdate'] is true. The value for localStorage['linrval'] is basically ignored.
Perhaps you want this:
if( localStorage['linrval'] || localStorage['linrdate'] ){...}
^^
You're also overwriting your localStorage values:
localStorage.setItem('linrval',inrval);
localStorage.setItem('linrdate',inrdate);

Related

jQuery check multiple CSV lists

To simplify my problem i rewrote the code without the parsing of CSV, but instead with a variable that holds the data.
--CODE EDIT---
$(document).ready(function() {
var qID = 'xxx';
var source = ['text1', 'text2', 'etc3'];
var source2 = ['text4', 'text5', 'etc6'];
$('#question' + qID + ' input[type="text"]').change(function() {
var validVal = 0;
var inputVal = $(this).val();
// Loop through the text and test the input value
$(source).each(function(i) {
if (inputVal == this) { // If a match is found...
validVal = 1;
}
});
// If a valid text was entered
if (validVal == 1) { // A valid input
alert("GOOD");
} else { // An invalid input
alert("NOT GOOD");
}
var validVal2 = 0;
var inputVal2 = $(this).val();
$(source2).each(function(j) {
if (inputVal2 == this) { // If a match is found...
validVal2 = 1;
}
});
// If a valid text was entered
if (validVal2 == 1) { // A valid input
alert("GOOD2");
} else { // An invalid input
alert("NOT GOOD2");
}
});
});
The script works fine for one source (var source) but i want to check in the same text field 2 variables (source, source2) that will produce different alerts.
The script is run through a limesurvey form and the input is a simple [type="text"] field.
How do I check for 2 different arrays of text in the same text field?
Whenever you find yourself putting counters on variable names to create a series, you need to stop and think about what you are actually doing there. Making counted variable names is always wrong.
Use arrays.
var qID = 'xxx';
var source = [];
source.push(['text1', 'text2', 'etc']);
source.push(['text1', 'text2', 'etc44']);
source.push(['text15', 'text25', 'etc454']);
$('#question' + qID + ' input[type="text"]').change(function() {
var valid = false;
var inputVal = $(this).val();
$.each(source, function(i, terms) {
$.each(terms, function(i, term) {
valid = inputVal === term;
return !valid; // returning false stops the .each() loop
});
return !valid;
});
if (valid) {
alert("GOOD");
} else {
alert("NOT GOOD");
}
});
A more appealing way to express the nested loop above uses built-in methods of Array.
var valid = source.some(function (terms) {
return terms.includes(inputVal);
});
in ES6 syntax this can be made a one-liner:
var valid = source.some(terms => terms.includes(inputVal));

Persist cookie form values across multiple pages

The setting: I have a form that captures$thisSearch.val(), saves it as a cookie, and pushes to an array. The form is an overlay triggered from a menu item in the header so this can appear on any page in the site.
The issue is that it only seems to save/persist the input values on/from that page it was entered on. I'm trying to collect all these values into one list.items() array that can be entered anywhere in the site.
I've tried pushing the string to the array myself instead of the add function and moved the dom around for the search form.
I can update question when I know what to specifically ask. Any pointers / concepts I should be aware of for this would be great.
var cookieList = function(cookieName) {
var cookie = $.cookie(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();
return {
"add": function(val) {
items.push(val);
$.cookie(cookieName, items.join(','));
},
"items": function() {
return items;
}
}
}
var list = new cookieList("PreviousSearches");
$searchSubmit.on('click', function() {
var $thisSearch = $(this).prev().find($searchInput);
if( $thisSearch.val() == '' ) {
alert('Please enter a search term');
console.log( list );
return false;
} else {
searchTerm = $thisSearch.val()
list.add( searchTerm );
}
});
var searchTerms = list.items();
var total = searchTermsFiltered;
var searchTermsFiltered = searchTerms.filter(Boolean).slice( - 5 ).reverse();
var searchtermClean = searchTermsFiltered.join();
$.each($(searchTermsFiltered), function(i,v){
if (!window.location.origin)
window.location.origin = window.location.protocol+"//"+window.location.host;
var lastURLRaw = window.location.origin+'/bch/?s='+v;
var lastURL = lastURLRaw.replace(/ /g, '+');
listItem = '<li>'+v+'</li>';
$('.tags, .search-tags').append(listItem );
});
I found the path specifier from jquerys $.cookie in this top answer below.
$.cookie(cookieName, items.join(',') , { path: '/' }); from my code.
why are my jquery cookies not available across multiple pages?

Why can't jQuery update array data before ajax post?

I am trying to create an array and get all values of a form submission and put them in that array. I need to do this because during the .each function of this code I must do additional encryption to all the values per client. This is a form with hundreds of fields that are changing. So it must be an array to work. I tried to do following and several other types like it in jQuery but no dice. Can anyone help? Thanks.
Edit: Posted my working solution. Thanks for the help.
Edit 2: Accept sabithpocker's answer as it allowed me to keep my key names.
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
Chack serializeArray() to see the JSON array format.
http://jsfiddle.net/kv9U3/
So clearly the issue is that this in your case is not the array as you suppose. Please clarify what this pointer refers to, or just verify yourselves by doing a console.log(this)
As you updated your answer, in your case this pointer refers to the form you submitted, how do you want to iterate over the form? what are you trying to achieve with the each?
UPDATE
working fiddle with capitalizing instead of encrypting
http://jsfiddle.net/kv9U3/6/
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
The problem is that #cja_form won't list its fields using each. You can use serialize() instead:
inputArray = jQuery(this).serialize();
Further edition, if you need to edit each element, you can use this:
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
Full code
jQuery(document).ready(function($){
$("#cja_form").submit(function(event){
$("#submitapp").attr("disabled","disabled");
$("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
$.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', input)
.success(function(result){
if (result.indexOf("success") === -1) {
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail">'+result+'</div>');
}
else {
page = document.URL;
if (page.indexOf('?') === -1) {
window.location = page + '?action=success';
}
else {
window.location = page + '&action=success';
}
}
})
.error(function(){
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
return false;
});
});
Original answer:
There are no associative arrays in javascript, you need a hash/object:
var input = {};
jQuery(this).each(function(k, v){
input[k] = v;
});
Here is my working solution. In this example it adds cat to all the entries and then sends it to the PHP page as an array. From there I access my array via $_POST['data']. I found this solution on http://blog.johnryding.com/post/1548511993/how-to-submit-javascript-arrays-through-jquery-ajax-call
jQuery(document).ready(function () {
jQuery("#cja_form").submit(function(event){
jQuery("#submitapp").attr("disabled","disabled");
jQuery("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var data = [];
jQuery.each(jQuery(this).serializeArray(), function(index, value) {
data[index] = value.value + "cat";
});
jQuery.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', {'data[]': data})
.success(function(result){
if (result.indexOf("success") === -1) {
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail">'+result+'</div>');
} else {
page = document.URL;
if(page.indexOf('?') === -1) {
window.location = page+'?action=success';
} else {
window.location = page+'&action=success';
}
}
})
.error(function(){
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
});
});

Show contents of localStorage into div

I have this basic function :
pid = 1;
$(function() {
if (localStorage["key"+pid] != null) {
var contentsOfDiv = localStorage.getItem("key"+pid);
$("#Div").html(contentsOfdDiv);
}
});
The problem is that the pid value will change eventually and I don't want to overwrite the contents of the key.
How can I proceed to stack every Div content that localStorage is saving for me ?
You can iterate on localStorage entries just like on any object properties :
for (var key in localStorage) {
console.log(key, localStorage[key]);
}
So your code could be :
$(function() {
var lines = [];
for (var key in localStorage) {
if (/^key/.test(key)) { // does the key start with "key"
lines.push(key.slice(3) + ' = ' + localStorage[key]);
}
}
$("#Div").html(lines.join('<br>'));
});
If I have understood well, you want to use pid to loop over the object.
Best way to do this and avoid for in chain prototypical problems is the following:
(I think for this case you are better with an array rather than with an object)
http://jsfiddle.net/hqkD9/
var localStorage = ['aaaa', 'bbbbb', 'cccc', 'dddd']; // don't forget to declare with var
var html_string = '';
$.each(localStorage, function(index, value) {
html_string += value + '<br>';
});
$('#my_div').html(html_string);

Open and close panels based on jQuery cookies

I have the following variables which store the value of a set of cookies:
var filterDate = $.cookie('filterDate');
var filterArea = $.cookie('filterArea');
var filterCategory = $.cookie('filterCategory');
var filterType = $.cookie('filterType');
var filterLevel = $.cookie('filterLevel');
var filterAge = $.cookie('filterAge');
var filterAttendance = $.cookie('filterAttendance');
The name of the cookies and variables are also the ids of some elements that are on the page so for example: <div id="filterDate"></div>
What I want to do is very minimally (i.e. less code as possible) is check if any have the value of open and if so then run the code inside.
if (filterDate == 'open' || filterArea == 'open' || filterCategory == 'open' || filterType == 'open' || filterLevel == 'open' || filterAge == 'open' || filterAttendance == 'open') {
$('#' + filter).find('.menuBox.nav ul').show();
$('#' + filter).find('.menuBox.nav p').hide();
$('#' + filter.find('h3 span').addClass('active');
}
How do I get the above to work as filter works for all the cookies without having to duplicate it per cookie and panel?
A compact solution may be:
//The array below allows you to easily add new filters
var filterNames = ["filterDate", "filterArea", ..., "filterAttendance"];
for (var i in filterNames) {
var filterName = filterNames[i];
var filterStatus = $.cookie(filterName);
if (filterStatus == 'open') {
$('#' + filterName).find('.menuBox.nav ul').show();
$('#' + filterName).find('.menuBox.nav p').hide();
$('#' + filterName.find('h3 span').addClass('active');
}
}
I wasn't clear if you were looking to trigger a different function based on the filter name. If so, you could store all the functions mapped to your cookies, then iterate over the names of the cookies, triggering the associated function if true: e.g.
var cookieList = ["filterDate", "filterArea"...];
var cookieMap = {"filterDate"=filterDateFn, "filterArea"=filterAreaFn...};
for (var i=0; i<numCookies; i++) {
if ($.cookie(cookieList[i]) == "open") {cookieMap[cookieList[i]]();}
if you only want to run one function, then you could skip making a cookieMap, and just run whatever success trigger you want, then break the for loop at that point.
Make an array of cookie names and then generate an object (map of key:pair values), where
the keys are the items from array and the values are the values of an appropriate cookies.
Then use loops to iterate through arrays/objects:
var filters = ['filterA', 'filterB', 'filterC'],
cookies1 = {},
cookies2 = {};
for(var i = 0, f; f = filters[i++];) {
// really here will be $.cookie(f); instead of 'open':
cookies1[f] = cookies2[f] = 'open';
}
// make one of second cookies set 'closed' for testing purpose:
cookies2['filterA'] = 'closed';
function allOpen(cookies) {
for(var i in cookies) {
if(cookies[i] != 'open') {
return false;
}
}
return true;
}
alert(allOpen(cookies1) + ', ' + allOpen(cookies2));
​

Categories

Resources