Show contents of localStorage into div - javascript

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);

Related

append table data into table using loop

I want to append table data that I have saved in local storage. I have tried this loop to add in its cells and loop through changing the numbers based on the count or rows it reads. here is my JS code:
$(function() {
$("#loadTask").change(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
var rows = $('#items-table tr').length;
var loop = 0;
var r = 1;
while (loop < rows) {
$("#items-table").append('<tr>'
+'<td>'+task.cells[r][0]+'</td>'
+'<td>'+task.cells[r][1]+'</td>'
+'<td>'+task.cells[r][2]+'</td>'
+'<td>'+task.cells[r][3]+'</tr>')
r += 1;
loop += 1;
}
})
})
this obviously does not work since im guessing when I JSON.Stringify the table data it saves it into one long string becuase when I added alert(row); before and after the loop I got 1 everytime even though the task had two rows.
Here is what I use to append the data into the table which I later save in local storage using a special name so I can save multiple different table datas :
function addRow() {
var item_text = $('#item-input').val();
var item_color = $('#color-input').val();
var size_text = $('#sizes-item').val();
var any_color = $('#any-color').is(':checked') ? 'Any Color' : '';
var any_size = $('#any-size').is(':checked') ? 'Any Size' : '';
$('#items-table').append('<tr>'
+'<td>'+item_text+', '+item_color+'</td>'
+'<td>'+size_text+'</td>'
+'<td>'+any_color+', '+any_size+'</td>'
+'<td><button class="remove-btn"><div class="thex">X</div></button><td>'
+'</tr>');
}
$(function(){
$('#add-item').click(function(){
addRow();
return false;
});
$('body').on('click', '.remove-btn', function(){
$(this).parent().parent().remove();
});
});
I thought that maybe since it wont count the table rows properly the only real thing that doesnt change at any table row is the remove button that gets added with every row.
So it tried changing
var rows = $('#items-table tr').length;
to:
var rows = $('#items-table button').length;
which I thought would work but when I added the alert part before and after the loop I got 0 every time.
What could I do to be able to count each row somehow to be able to append them properly back into the table the same way they were added in.
here is the javascript that saves the table data into localStorage:
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call($("#items-table")[0].rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = {
cells: cells
};
var itemCount = $("#items-table tr").length - 1;
var lengthrows = {
itemCount: itemCount
}
saveLength(lengthrows);
var rowsCount = loadLength()
alert(rowsCount);
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function saveLength(lengthrows) {
var count = localStorage.getItem('lengthrows');
if (!count || typeof(count) !== "object")
savedCount = {};
savedCount[task.Name] = task;
localStorage.setItem('itemCount', savedTasks);
}
function loadLength(taskName) {
var lengthCount = localStorage.getItem("itemCount");
return lengthCount[taskName];
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks) {
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
});
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
//Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
I am also trying to save the count of the rows in each specific task. The stuff I attempted below with the saveLength doesn't work any suggestions?
Any help is appreciated Thank You <3
Your code when you need load task might be looks like that:
$(function() {
$("#loadTask").change(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
var rows = task.cells;
let tpl = (rows) => {
return rows.slice(1).map(e => '<tr>' + e.map(e => `<td>${e}</td>`) + '</tr>');
}
$("#items-table").append(tpl(rows));
})
})
For removing tasks you need to add removeTask function which i've wrote:
function removeTask (taskName) {
var tasks = JSON.parse(localStorage.getItem('tasks'));
if (typeof tasks !== "object")
return false; // our tasks list not set. return negative.
delete tasks[taskName];
$('#loadTask > option:contains(' + taskName + ')').remove();
localStorage.setItem('tasks', JSON.stringify(tasks));
return true;
};
And modify your click listener at .remove-btn. Your listener should be look like that:
$('body').on('click', '.remove-btn', function(){
$(this).parent().parent().remove();
if ($('#items-table > tbody').children().length < 2) {
console.log("attemping to remove...");
if (removeTask($("#loadTask").val()))
alert('Task successfully removed.');
}
});

how to remove the chrome.storage.local

Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};

Can't update javaScript global variable

Here I have global variable userId, and i want to update it inside signInUserFunction(), to use is in other function. I have tried to define it using var, window, But all these didn't help. This variable doesn't update. As i see its about AJAX async. So, what can i do with it?
And yes, I know that its not good to make authentication with JS, I am quite new to it. So, I am just creating random methods to improve.
var userId = 1;
function signInUser() {
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data) {
var items = [];
var i = 0;
$.each(data, function(firstname, value) {
var str = JSON.stringify(value);
data = JSON.parse(str);
var innerId;
for (p in data) {
innerId = data[p].id;
if ($('#nameSignIn').val() == data[p].first_name && $('#passwordSignIn').val() == data[p].password) { //
userId = innerId;
window.location.href = "content.html";
break;
} else {
i++;
if (i == data.length) {
alert("Ощибка в логине или пароле!")
}
}
}
});
});
}
How are you determining whether or not it has been set? It looks like immediately after you set it, you navigate to a different page. When you get to that page, you will have an entirely new window.
Try alerting the value before navigating away.
EDITED: Here is how you could pass it to the other page (but you shouldn't do this in a real app)
window.userId=innerId;
alert(window.userId);
//this isn't a very secure way to do this. I DON'T recommend this
window.location.href = "content.html?id=" + innerId ;
Then in the other page, you could access it off the document.location:
alert(document.location.toString().split("?id=")[1]);
After reading my comments, you may want to try this:
var userId = 1;
function signInUser(){
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data){
var items = [], actors = data.Actors, l = 0;
$.each(actors, function(i, o){
l++;
if($('#nameSignIn').val() === o.first_name && $('#passwordSignIn').val() === o.password){
userId = o.id;
// this will redirect before any other code runs -> location = 'content.html';
if(l === actors.length){
alert('End of Loop');
}
}
});
});
}
signInUser();
I would not store sensitive data in JSON such as passwords. Use a database. There is no need to get all the data at the same time either.
Using the idea #mcgraphix proposed (and giving you the same warning...this would certainly not be the way to transfer data like this in a production environment), here is one way to do it:
function signInUser() {
var url = 'http://localhost:8887/JAXRSService/webresources/generic/getAllUsers';
var userId;
$.getJSON(url, function(data) {
$.each(data.Actors, function(index, actor) {
// Cache the values of the #nameSignIn and #passwordSignIn elements
var name = $('#nameSignIn').val();
var password = $('#passwordSignIn').val();
if (actor.first_name === name && actor.password === password) {
// We have found the correct actor.
// Extract its ID and assign it to userId.
userId = actor.id;
window.location.href = "content.html?userId=" + userId;
}
});
// This alert should only be reached if none of the actor objects
// has a name and password that matches your input box values.
alert("Ощибка в логине или пароле!");
});
}
// On the next page...
// Top answer from http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
// This approach can handle URLs with more than one query parameter,
// which you may potentially add in the future.
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
var userId = getQueryVariable('userId');
Thanks you for help.Ended it all with usage of:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')

How can I save javascript variables locally?

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);

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;
});
});

Categories

Resources