Working with Localstorage for put content in table (JQuery) - javascript

I have a big problem working with this.
I have a table in my html, in my js I'm using localstore (I have never used that before)
I insert a new row, and it is stored with localstore, I create a JSON.
For putting the ID of the raw, I just get the length of my localstorage.
For example, I have 3 rows, with IDs 1, 2 and 3.
If I decide to delete one, we can say the number 2, I can delete it, yeah, but the next time when I create a new raw I'll have the id = 2.
why?, because I use localstorage.length+1 for putting the id, so... If I had 3 before, the next time I'll get a 3, I'll replace my content where ID = 3.
what can I do for avoid that mistake?
my JS is this
crearTabla(tablastorage)
$("#btnNuevo").on('click',function(){
$("#mymodal1").modal("show");
$('#btnGuardar').data('evento','crear');
});
$("#btnCargar").on('click',function(){
crearTabla(tablastorage)
});
$("#btnGuardar").on('click',function(){
if($(this).data('evento') == "crear"){
Crear();
$('input:text').val('');
}
else{
Modificar();
}
$("#mymodal1").modal("hide");
});
function crearTabla(data){
$("#tabla").empty();
$.each(data, function(index, val){
var temp = JSON.parse(val);
var $tr = $("<tr/>");
var $tdID = crearTD(temp.id);
var $tdMatricula = crearTD(temp.matricula);
var $tdNombre = crearTD(temp.nombre);
var $tdSexo = crearTD(temp.sexo);
var $tdAccion = crearAccion(temp);
$tr.append($tdID, $tdMatricula, $tdNombre, $tdSexo, $tdAccion);
$("#tabla").append($tr);
$('input:text').val('');
})
}
function Crear(){
var $tr = $("<tr/>");
var $tdID = crearTD(tablastorage.length+1);
var $tdMatricula = crearTD($("#matricula").val());
var $tdNombre = crearTD($("#nombre").val());
var $tdSexo = crearTD($("#sexo").val());
var JSon = {
id:tablastorage.length+1,
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
if($('#matricula').val()=='' || $('#nombre').val()=='' || $('#sexo').val()==''){
alert("Uno o mas campos vacios");
}
else{
tablastorage.setItem(tablastorage.length, JSON.stringify(JSon))
var $tdAccion = crearAccion(JSon);
crearTabla(tablastorage)
$('input:text').val('');
}
};
function crearTD(texto){
return $("<td/>").text(texto);
};
function crearAccion(objeto){
var $td = $("<td/>");
var $div = $("<div/>",{
class:'btn-group',
role:'group'
});
var $btnElminar = $("<button/>",{
class:'btn btn-danger eliminar'
}).html("<i class='glyphicon glyphicon-remove'></i>"
).data('elemento',objeto);
var $btnModificar = $("<button/>",{
class:'btn btn-info modificar'
}).html("<i class='glyphicon glyphicon-pencil'></i>"
).data('elemento',objeto);
$div.append($btnElminar, $btnModificar)
return $td.append($div);
};
$("#tabla").on('click','.eliminar',function(event){
console.log($(this).data('elemento').id)
tablastorage.removeItem($(this).data('elemento').id-1)
crearTabla(tablastorage)
});
$("#tabla").on('click','.modificar',function(event){
index = $(this).data('elemento').id-1;
var $elemento = $(this).data('elemento');
$('#btnGuardar').data('evento','modificar');
$('#id').val($elemento.id);
$('#matricula').val($elemento.matricula);
$('#nombre').val($elemento.nombre);
$('#sexo').val($elemento.sexo);
$("#mymodal1").modal("show");
});
and my html have this code:
http://notes.io/wAYL
Two extra things.
1. Sorry for my bad english, If I've made a mistake is because I speak spanish, not english all the time, I need to improve my skills with the languague.
2. Also because I don't know how to put the code here. I just tried and I faild so many times.
<-- Please don't erase this -->

What i usually do is store whole arrays in one storage key as JSON.
When you load page you get whole array using something like:
var data = JSON.parse( localStorage.getItem('tableData') || "[]");
$.each(data, function(_, item){
// append html to table for each item
});
Then in your Crear() you would push the new item into the array, and store the whole array
var JSon = {
id: +new Date(),
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
data.push(JSon);
localStorage.setItem('tableData', JSON.stringify(data));
Similar to remove an item , splice() the array to remove it from main array and store again.
One suggestion for ID is use current timestamp

Related

Why does my for loop return only one result

The value of the search is supposed to append to the nyt api and the for loop is supposed to list all the links. I'm only getting one result for some reason but when looked through console I see that there 100s of links.
function myFunction(){
var citySearch = $("#city").val();
var NYTurl = "https://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + citySearch +
"$sort=newest&api-key=xxxxxxxxxxxxxxxxxxxxxxxx"
jQuery.getJSON(NYTurl, function (data){
var headlines = $("#headlines")
var contentUrl = data.response.docs
for(var i = 0; i < contentUrl.length; i++ ){
contentUrlLoop = contentUrl[i];
headlines.html('Link' );
}
console.log(data)
})
return false;
}
headlines.html( assigns the passed HTML string to headlines's inner HTML. So, on each iteration, you're overwriting whatever headlines had previously. Use append instead if you want to insert an <a> for every item in the response:
headlines.append('Link' );
Or, rather than making hundreds of DOM changes, you might consider coming up with a single HTML string and then appending it:
jQuery.getJSON(NYTurl, function(data) {
var headlines = $("#headlines");
var contentUrl = data.response.docs;
var htmlStr = contentUrl.reduce(
(a, { web_url }) => a + 'Link',
''
);
headlines.html('Link');
});
(perhaps enclose them in divs as well so that each link is on a new line, or make the as block, so that the HTML is readable)

How to save a HTMLElement (Table) in localStorage?

I've been trying this for a while now and could not find anything online...
I have a project, where tablerows get added to a table. Works fine.
Now I want to save the Table in the localStorage, so I can load it again. (overwrite the existing table).
function saveProject(){
//TODO: Implement Save functionality
var projects = [];
projects.push($('#tubes table')[0].innerHTML);
localStorage.setItem('projects', projects);
//console.log(localStorage.getItem('projects'));
The problem is the Array "projects" has (after one save) 2000+ elements. But all I want is the whole table to be saved to the first (or appending later) index.
In the end I want the different Saves to be listed on a Option element:
function loadSaveStates(){
alert('loading saved states...');
var projects = localStorage.getItem('projects');
select = document.getElementById('selectSave'); //my Dropdown
var length = projects.length,
element = null;
console.log(length);
for (var i = 0; i < length; i++) {
element = projects[i];
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = 'project ' + i;
select.appendChild(opt);
}
}
Can anyone tell me what I am doing wrong?
You can easily do this by jquery, are you interested in this, if yes.. then try following code
For setting the value
$.jStorage.set("projects", $.trim(projects));
For Getting the data
$.jStorage.get("projects");
For deleting the data with key
$.jStorage.deleteKey("projects");
I coose to stay with localStorage, but insted of using an Array I just let the user give every project a name and create a new Item for every Save:
function saveProject(){
//TODO: Implement Save functionality
var pname=prompt("Please enter your project name:","projectname")
var text = $('#mainTable')[0].innerHTML;
//console.log(text);
localStorage.setItem(pname, text);
//console.log(localStorage.key(2));
loadSaveStates();
}
function loadProject(){
var selected = $('#selectSave')[0].selectedIndex
//console.log(selected);
if (localStorage.key(selected) == 'jStorage'){
selected++;
}
var innerHTMLTable = localStorage[localStorage.key(selected)];
//console.log(innerHTMLTable);
$('#mainTable')[0].innerHTML = innerHTMLTable;
updateHandlers();
}
function deleteProject(){
var selected = $('#selectSave')[0].selectedIndex
var pname = $('#selectSave')[0].options[selected].value
$('#selectSave')[0].remove(selected);
localStorage.removeItem(pname);
//console.log(pname);
loadSaveStates();
}

Trying to count SharePoint List Values with JavaScript

Hello stack overflow community...
Thanks for all of the help that you have provided so far even though I have never posted on this site. I am a beginner... so that means most of the stuff that I have gotten to work has come after trying to shove a square peg into a round hole too many times to count until finally the edges are worn off enough that it actually fits...
Anyway... due to the Today() issue with SharePoint and the need to base data comparison against the current date/time I have been struggling to write my own code and display the data as I would like to in the SharePoint site that I have access too.
So far I have everything working as intended with one little flaw...
I cannot figure out how to count values even though I can make comparisons between two values. I believe it has something to do with how data is being retrieved from the SharePoint list rows and appended to the HTML table.
Relevant sections of code are as follows:
$(document).ready(function () {
$().SPServices({
operation: "GetListItems",
async: false,
CAMLRowLimit: 20,
listName: "Announcements",
completefunc: FirstFunc
});
});
function FirstFunc(xData, Status) {
var index = 0;
$documentListtable = $("#tableFirstFunc");
$(xData.responseXML).find("z\\:row, row").each(function () {
var LOTOSPLink =$(this).attr("ows_LOTODocLink");
var _Title = $(this).attr("ows_Title");
var ahref = "<a href='" + LOTOSPLink + "'>";
var anchor = "</a>"
var Titles = ahref + _Title + anchor
//Start of AReview
var _AReview = $(this).attr("ows_AReview");
var astartDateTime = $(this).attr("ows_AReview");
var astartDate = $(this).attr("ows_AReview").split(" ")[0];
var astartTime = $(this).attr("ows_AReview").split(" ")[1];
var astartDateParts = astartDate.split("-");
var aSPDYear = astartDateParts[0];
var aSPDMonth = astartDateParts[1];
var aSPDDay = astartDateParts[2];
var aSPDJoin = aSPDMonth+'/'+aSPDDay+'/'+aSPDYear;
var astartTimeParts = astartTime.split(":");
var aSPTHour = astartTimeParts[0];
var aSPTMin = astartTimeParts[1];
var aSPTSec = astartTimeParts[2];
//Combine SharePoint Date & Time split parts back together in JS Date Object
//format and than convert to millisecons to compare dates
var aReviewGraphic = ""
if(aSPDTValue === 18000000) {
aReviewGraphic="<img src="sites/Somesite/NAGlassyButton20.png>";
}
else if(aSPDTValue >= firstDCMonth && aSPDTValue < lastDCMonth) {
aReviewGraphic="<img src="/sites/Somesite/GreenButtNew20.png>";
}
else if(aSPDTValue >= firstDCYear && aSPDTValue < firstDCMonth) {
aReviewGraphic="<img src="/sites/Somesite//GreenButtOld20.png>";
}
else if(aSPDTValue < firstDCYear) {
aReviewGraphic="<img src="/sites/Somesite/RedButt20.png>";
}
var $row = $("#templates").find(".row-template").clone();
$row.find(".Titles").html(Titles);
$row.find(".aReviewGraphic").html(aReviewGraphic);
$row.find(".bReviewGraphic").html(bReviewGraphic);
$row.find(".cReviewGraphic").html(cReviewGraphic);
$row.find(".dReviewGraphic").html(dReviewGraphic);
$row.find(".NewModiDReviewGraphic").html(NewModiDReviewGraphic);
$documentListtable.append($row);
});
}
I am changing the graphics in the tables as intended, the data is being displayed as desired... but I cannot figure out how to perform a count. It seems like the rows are being read one at a time and being put into the HTML table one after the other and that all comparisons are being done row by row. I say that because my alert(messages) are being triggered for each row of data pulled in from the sharepoint list.
Is there a way to store this data in an array locally... surely there is some way to do this but I am new enough to this that I don't even know the right questions to ask...
Also the 18000000 in the if statement is the 1/1/1970 test date that I am using to currently test with as I found that any fields that were blank in the sharepoint list would cause the query to quit returning any rows after that. My solution was to use the 1/1/1970 as the default value and use it the same as leaving the field blank. I am sure that this is a crude method to work a round a problem that is easy to fix but it was all I could come up with.
Any help would be appreciated...
Steve
I try to understand... My suggestion is to store all your html into a variable and then inject the code into the table.
// somewhere you should have your HTML code
// <table id="templates"></table>
$(document).ready(function () {
$().SPServices({
operation: "GetListItems",
async: false,
CAMLRowLimit: 20,
listName: "Announcements",
completefunc: FirstFunc
});
});
function FirstFunc(xData, Status) {
var index = 0;
$documentListtable = $("#tableFirstFunc");
// create a variable where to store the html code
var htmlData = "";
// go thru the data received by the query
$(xData.responseXML).find("z\\:row, row").each(function () {
// we look at one row
var LOTOSPLink =$(this).attr("ows_LOTODocLink");
var _Title = $(this).attr("ows_Title");
var ahref = "<a href='" + LOTOSPLink + "'>";
var anchor = "</a>"
var Titles = ahref + _Title + anchor
//Start of AReview
var _AReview = $(this).attr("ows_AReview");
var astartDateTime = $(this).attr("ows_AReview");
var astartDate = $(this).attr("ows_AReview").split(" ")[0];
var astartTime = $(this).attr("ows_AReview").split(" ")[1];
var astartDateParts = astartDate.split("-");
var aSPDYear = astartDateParts[0];
var aSPDMonth = astartDateParts[1];
var aSPDDay = astartDateParts[2];
var aSPDJoin = aSPDMonth+'/'+aSPDDay+'/'+aSPDYear;
var astartTimeParts = astartTime.split(":");
var aSPTHour = astartTimeParts[0];
var aSPTMin = astartTimeParts[1];
var aSPTSec = astartTimeParts[2];
//Combine SharePoint Date & Time split parts back together in JS Date Object
//format and than convert to millisecons to compare dates
var aReviewGraphic = "";
// I don't understand why you use this variable that hasn't been initialized...
if (aSPDTValue === 18000000) {
aReviewGraphic='<img src="sites/Somesite/NAGlassyButton20.png>';
}
else if(aSPDTValue >= firstDCMonth && aSPDTValue < lastDCMonth) {
aReviewGraphic='<img src="/sites/Somesite/GreenButtNew20.png>';
}
else if(aSPDTValue >= firstDCYear && aSPDTValue < firstDCMonth) {
aReviewGraphic='<img src="/sites/Somesite//GreenButtOld20.png>';
}
else if(aSPDTValue < firstDCYear) {
aReviewGraphic='<img src="/sites/Somesite/RedButt20.png>';
}
htmlData += '<tr><td class="Titles">'+Titles+'</td><td class="aReviewGraphic">'+aReviewGraphic+'</td><td class="bReviewGraphic">'+bReviewGraphic+'</td><td class="cReviewGraphic">'+cReviewGraphic+'</td><td class="dReviewGraphic">'+dReviewGraphic+'</td><td class="NewModiDReviewGraphic">'+NewModiDReviewGraphic+'</td></tr>';
// you can increment your index if you want
index++;
});
alert("There are "+index+" rows");
// add the HTML data into the table
$documentListtable.append(htmlData);
}

How do I retrieve the first value from an array?

I have a call to a YouTube XML sheet that works perfectly fine. However, I am having trouble setting a value from one of the arrays. I want the first value from "songID" to be set as "first". I've tried doing this:
var first = songID[0]
but it only makes a new array with only the first character of each value... Any suggestions?
$(window).load(function(){
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/F9183F81E7808428?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
}
}
})
You are already in an each() loop, so you shouldn't try to access it as an array, but just as a value. Just try:
if(i == 0){
var first = songID;
}
Are you sure what you're getting is actually an array? What makes you think that? Because if you ask for aString[0], you'll still get the first character back, because you can access string characters as if they're array elements. If it is indeed an array, just use var myString = myArray.join(""); and it'll become a string.
$(document).ready(function() {
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
if(i==0){
alert("firstId is "+songID );
}
});
});
});
or just for first id:
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
console.log(data.feed.entry[0].media$group.media$content[0].url.substring(25, [36]));
});
});

Javascript 2D array issue - all elements are a copy of the final entry

I'm creating a javascript 2D array from an XML file which I then manipulate and filter as necessary before displaying on the page.
As I loop through the XML records, I manipulate the data a little, build a normal array from it (rowRecord) and then add this array to the 2D array (dataSet). Thing is, I end up with a nice 2D array, but all the records are duplicates of the very last record I'm adding.
Using some alerts I've found that as I add the first record, all is well. I then add the second record and I get a dataSet with 2 records, both of which are record 2. Adding the third results in a dataSet of 3 records, each of them a copy of the third record. This carries on for all 1300 records, resulting in 1300 identical records, all of which are the last record from the XML.
Here is the code:
var rowRecord = new Array();
var dataSet = new Array(rowRecord);
function getAjaxTridionInfo() {
var xmlFilename = 'filename.xml';
// make ajax call here, create xml object
xmlData = new Ajax.Request(xmlFilename,{
method:'get',
onSuccess: function(transport) {
var dataObj = transport.responseXML;
var vRoot = dataObj.getElementsByTagName('Items')[0];
for (var i=0; i<vRoot.childNodes.length; i++) {
if (vRoot.childNodes[i].nodeType == 1) {
var tridItem = vRoot.childNodes[i];
rowRecord[0] = tridItem.childNodes[0].firstChild.nodeValue.substring(26);
rowRecord[1] = tridItem.childNodes[1].firstChild.nodeValue;
rowRecord[2] = tridItem.childNodes[2].firstChild.nodeValue;
rowRecord[3] = rowRecord[1]+"/"+rowRecord[2];
rowRecord[4] = false;
rowRecord[5] = "n/a";
rowRecord[6] = "n/a";
rowRecord[7] = false;
rowRecord[8] = "n/a";
rowRecord[9] = "n/a";
//do some other processing here to determine rowRecord[4] - [9]
dataSet.push(rowRecord);
rowCount += 1;
}
}
//call next function here
},
onException: function(transport, exception) {
throw(exception);
alert('There has been a problem performing the Ajax call');
}
}
);
}
Any help or suggestions would be appreciated.
You should create rowRecord in the function, not outside, so as to make a new array for every row record.
// NO NEED TO DECLARE ROWRECORD HERE...
var dataSet = new Array(); // <- why would we add anything initially?
function getAjaxTridionInfo() {
// ...
if (vRoot.childNodes[i].nodeType == 1) {
var tridItem = vRoot.childNodes[i];
// IMPORTANT TO MAKE A NEW ARRAY HERE
var rowRecord = new Array();
rowRecord[0] = tridItem.childNodes[0].firstChild.nodeValue.substring(26);
rowRecord[1] = tridItem.childNodes[1].firstChild.nodeValue;
rowRecord[2] = tridItem.childNodes[2].firstChild.nodeValue;
rowRecord[3] = rowRecord[1]+"/"+rowRecord[2];
rowRecord[4] = false;
rowRecord[5] = "n/a";
rowRecord[6] = "n/a";
rowRecord[7] = false;
rowRecord[8] = "n/a";
rowRecord[9] = "n/a";
//do some other processing here to determine rowRecord[4] - [9]
dataSet.push(rowRecord); // <- PUSHES THE NEW ARRAY
rowCount += 1;
}
// ...
}
Move:-
var rowRecord = new Array();
to just before:-
rowRecord[0] = tridItem.childNodes[0].firstChild.nodeValue.substring(26);
Otherwise you keep re-using the same instance of an array object, overwriting its content on every iteration. All entries in the outer array point to this same single instance of the array.
Change:
var dataSet = new Array(rowRecord);
to:
var dataSet = [];
UPDATE: And move the dataSet declaration as per #AnthonyWJones

Categories