I have made a localStorage with a user_name login and i have parsed the string of my JSON data (entry) to a plain object.
But if I try to console log entry.username i get my stored users but also get a "undefined"?
I suspect that is my User:index code that is messing up the entry.user_name?
var User = {
index: window.localStorage.getItem("User:index"),
$form: document.getElementById("userReg"),
$button_register: document.getElementById("registerUser"),
$button_login: document.getElementById("logIN"),
init: function() {
// initialize storage index
if (!User.index) {
window.localStorage.setItem("User:index", User.index = 1);
}
User.$form.addEventListener("submit", function(event) {
var entry = {
id: parseInt(this.id_entry.value),
user_name: this.user_name.value,
};
if (entry.id == 0) {
User.storeAdd(entry);
}
}, true);
User.$button_login.addEventListener("click", function(entry) {
for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i);
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
}
if (document.getElementById("firstName").value == entry.user_name) {
alert("You have logged in");
} else {
document.getElementById("negative").innerHTML = "Username does not match"
}
}, true);
},
storeAdd: function(entry) {
entry.id = User.index;
window.localStorage.setItem("User:index", ++User.index);
window.localStorage.setItem("User:" + entry.id, JSON.stringify(entry));
},
};
User.init();
The issue is the data in localStorage. Your login function assumes that all entries stored in localStorage will be of your User entry type. But when you start storing other things, you have no checking to confirm the type is what you expect.
Here:
for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i);
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
}
The line that is actually failing is: entry = JSON.parse(window.localStorage.getItem(key)); because at the end of the loop, the type in localStorage is User:index, not User:3.
If you plan on having more things in localStorage, you should add a check in your loop, such as this:
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i);
var reg = new RegExp("User\:\\d+$");
//Only process user entries
if(reg.test(key)) {
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
console.log(entry);
} // end if
}
Here is a fiddle: http://jsfiddle.net/xDaevax/Lo63vftt/
Disclaimer: I changed some other things to in order for it to work more efficiently for a fiddle, you can ignore the other changes I made.
You are right it is the User:index causing this issue. You can fix it with the following code.
for(var i = 1; i < User.index; i++) {
var key = "User:" + i;
var entry = JSON.parse(localStorage[key]);
console.log("entry : ", key, entry);
...
http://jsfiddle.net/yv04x4mw/6/
May I also recommend not creating accounts this way (unless you have a good reason), also use a JavaScript library like jQuery.
Related
I'm using pdfjs to display a PDF form (acroforms example). If I fill in some fields, how do I get those annotations.
I've tried:
pdfPage.getAnnotations().then(function(a) {
for(var i = 0;i < a.length; i++) {
console.log(a[i].id + ' - ' + a[i].fieldValue);
}
});
But all I get are empty fieldValues. I guess I'm getting them from the original PDF. How do I access the live document which includes the new annotations?
async getAnnotations() {
var result = {};
var pages = PDFViewerApplication.pdfDocument.numPages;
for (var i = 1; i <= pages; i++) {
var page = await PDFViewerApplication.pdfDocument.getPage(i);
var annotations = await page.getAnnotations();
for (var j = 0; j < annotations.length; j++) {
var element = annotations[j];
// Field Name
if (result[element.fieldName] == null) {
result[element.fieldName] = null;
}
var val = PDFViewerApplication.pdfDocument.annotationStorage.getOrCreateValue(element.id);
if (element.radioButton) {
if (val.value) {
result[element.fieldName] = element.buttonValue;
}
} else if (element.checkBox) {
result[element.fieldName] = val.value ? "On" : "Off";
} else {
result[element.fieldName] = val.value;
}
}
};
return result;
}
You should save values written by user in a local variable
Then you should create a xfdf file ( xml file by Adobe ) , look for Example nere : https://developer.salesforce.com/page/Adobe_XFDF . The xfdf should then be merged with original pdf to produce a new compiled pdf
I keep array localstorage. I want to delete an element from the array list on another page. My code is below but delete function does not work why?
push.js
existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
entry = {
"adi":path,
};
localStorage.setItem("entry", JSON.stringify(entry));
existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
delete.js
delete: function (e) {
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if (dataSource[i].adi == del) { dataSource.splice(i, 1); }
}
// insert the new stringified array into LocalStorage
localStorage.getItem("allEntries") =
JSON.stringify(existingEntries);
}
var dataSource = JSON.parse(localStorage.dataSource); //whatever data you want
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if(del === persons[i].name){ //look for match with name
dataSource.splice(i, 1);
break; //exit loop since you found the person
}
localStorage.getItem("allEntries") = JSON.stringify(existingEntries); // insert the new stringified array into LocalStorage
}
I am trying to create a customizable list with links that can be hidden using a class if you click in a button. Also the list have a sortable option that you can move the links on the list, which saves to localstorage.
The problem is that I don't know how to save the class change with the list order in the localstorage if you click the "add/remove" button on each li.
Also, if anyone can help me improve the code I will be grateful, I am a newbie with localstorage and only managed this with a lot of reading in tutorials and documentation.
Here's a working example:
http://codepen.io/RogerHN/pen/EgbOzB
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
list.appendChild(itemsArr[i]);
}
}
}
}
$('.list-block.sortable').on('sort', function () {
var newIdsOrder = [];
$(this).find('li').each(function(){
newIdsOrder.push($(this).attr('data-id'));
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newIdsOrder));
});
You want something like this:
var myApp = new Framework7({
swipePanel: 'left'
});
// Export selectors engine
var $$ = Dom7;
var mainView = myApp.addView('.view-main');
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
var classes = JSON.parse(localStorage.getItem('classes') || '["","","","","","","","","",""]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
itemsArr[i].className = classes[i];
list.appendChild(itemsArr[i]);
// handle [add/remove] thing
if (classes[i] != "") {
$(itemsArr[i]).find(".checky").removeClass("selected");
}
}
}
}
}
$('.list-block.sortable').on('sort', saveInfo);
$(".restore").click(function(e) {
$(".confirm").show();
$(".shadow").show();
});
$(".no,.shadow").click(function(e) {
$(".confirm").hide();
$(".shadow").hide();
});
$(".yes").click(function(e) {
$(".confirm").hide();
});
$(".lbl").click(function(e) {
$(".toggle-text").toggleClass("blue");
$(".restore").toggle();
$(".checky").toggle();
$("li.hidden").toggleClass("visible");
});
$('.checky').click(function() {
if (!$(this).hasClass("selected")) {
$(this).parent().removeClass("hidden").addClass("visible");
}
else {
$(this).parent().addClass("hidden visible");
}
$(this).toggleClass("selected");
saveInfo();
});
function saveInfo() {
var newUserList = [];
var newClassList = [];
$("#linklist").find('li').each(
function() {
newUserList.push($(this).attr('data-id'));
if ($(this).hasClass("hidden")) {
newClassList.push("hidden");
}
else {
newClassList.push("");
}
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newUserList));
localStorage.setItem('classes', JSON.stringify(newClassList));
console.log("saved.");
}
function reset() {
console.log("Removing data from local storage.");
localStorage.setItem('userlist', '["1","2","3","4","5","6","7","8","9","10"]');
localStorage.setItem('classes', '["","","","","","","","","",""]');
window.location.reload(true);
};
Codepen
Technically, I should've added explanation...
I'm fetching data from SharePoint using REST, and everything works just fine, except that I would like to count the times the same item appears.
This is the jQuery:
var url = "https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=TypeOfIssueValue asc,StatusValue desc&$filter=StatusValue ne 'Completed'&groupby=TypeOfIssueValue/StatusValue";
var lastIssue = '';
$.getJSON(url, function (data) {
$('#totalCounter').text(data.d.results.length);
for (var i = 0; i < data.d.results.length; i++) {
var dateReceived = data.d.results[i].DateReceived;
dateReceived = new Date(parseInt(dateReceived.replace("/Date(", "").replace(")/", ""), 10)).toLocaleString('en-US', {
year: 'numeric',
month: 'numeric',
day: '2-digit'
});
var issue = data.d.results[i].TypeOfIssueValue;
console.log(data.d.results[i].TypeOfIssueValue);
if (issue != lastIssue) {
lastIssue = issue;
$('#myDataList').append('' + issue + '<span class="badge">' + issue.length + '</span>');
}
}
});
I need to count how many time a specific TypeOfIssueValue appears. When I see the console it shows exactly what I would like to add to me info:
I just added a issue.length in the badge were I want to insert the number for the sake of just having something there, but I know it won't show what I want. Thanks!
var data = {
d: {
results: [
{ TypeOfIssueValue: '456' },
{ TypeOfIssueValue: '123' },
{ TypeOfIssueValue: '789' },
{ TypeOfIssueValue: '123' }
]
}
};
var filteredItems = data.d.results.filter(function(item){
return item.TypeOfIssueValue == '123';
});
var count = filteredItems.length;
document.getElementById("output").innerHTML = "Number of items with value '123': " + count;
<div id="output"/>
You could first map the TypeOfIssueValue values to a new array and then count each occurence based on this answer.
The code would be :
var a = data.d.results.map(function(issue) {
return issue.TypeOfIssueValue
});
result = {};
for (i = 0; i < a.length; ++i) {
if (!result[a[i]])
result[a[i]] = 0;
++result[a[i]];
}
The result will be an object with property being type of issue and value being the count of each.
Let me know if this makes sense.
Thanks #srinivas. I accepted your response, although I made some modifications, just in case they are useful to someone else.
I added a class to the span badge and added a new array to push the issues:
issuesArray.push(data.d.results[i].TypeOfIssueValue);
$('#myDataList').append('' + issue + '<span class="badge badgeSpan"></span>');
Then I addded a done() to run after the getJSON:
.done(
function(){ var resultado = foo(issuesArray)[1];
console.log(resultado);
var badges = $('.badgeSpan');
for (var j = 0; j < resultado.length; j++){
badges[j].innerHTML = resultado[j];
}
});
Last I made a small modificfation to the function foo() that you provided:
testArray = [];
function foo(arr) {
var a = [], b = [], prev;
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
testArray.push(a,b)
return testArray;
}
This maybe a very unorthodox solution, but it worked for me. Thanks again.
I have a function which is called when a file is needed to be read in a folder. In this case since i have 3 files in that folder, it is called 3 times consecutively. I need to save all files info into array mapped_data2 like that:
mapped_data2[0] = inner_data1 //first file info,
mapped_data2[1] = inner_data2 //second file info etc.
However using my code i am having just the first files information 3 times. I am a bit confused with global variables, if you can point out the problem, i would appreciate it.
here is the code:
var mapped_data = [];
var mapped_data2 = [];
function o(msg) {
if (msg.data) {
var inner_data = [];
var lines = msg.data.split('\n'); //read lines of a file
for (var i = 2; i < lines.length; i++) {
if (lines[i].length > 0) {
.. //do same data format here
inner_data.push([son, vactual, voutput]);
}
}
mapped_data = inner_data;
}
else {
if (msg.topic == "/somefolder/somefolder") {
for (var i = 0; i < msg.args.length; i++) {
var filename = msg.args[i];
aw.get(filename);
}
}
}
}
function de() { //where i wanted to use these files info
for (var i = 0; i < 3; i++) {
mapped_data2[i] = { key: "Group" + (i + 1), values: mapped_data };
}
var datam = mapped_data2;
var den = JSON.stringify(datam);
document.write(den);
};
function init() {
..//create new client called aw for the server application and start it;
..//if the connection is established:
aw.onmessage = o;
aw.get("/somefolder/somefolder"); // request list of files in a folder
};
//when html page is being onload, call the functions init() and de()
var mapped_data2 = [];
function o(msg) {
var mapped_data = []; // this doesn't need to be global
if (msg.data) {
var inner_data = [];
...
mapped_data = inner_data;
} else {
...
}
mapped_data2.push({ key: "Group" + mapped_data2.length + 1, values: mapped_data };)
// do more stuff as in den()
}