array from localStorage and display in a table - javascript

I am getting the data not in the right column. What is the right way to do this?
//store the data into localStorage
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" +
JSON.parse(localStorage.getItem(key)) + "</td></tr>\n";
}
if (list == "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}
/*
* Checking the browser compatibility.
*/
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// we can use localStorage object to store data
return true;
} else {
return false;
}
}
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */

After you parse the JSON, you need to extract the data and item so you can show them in separate table columns.
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
if (localStorage.length == 0) {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td><td><i>empty</i></td></tr>\n";
} else {
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
let data = JSON.parse(localStorage.getItem(key));
list += "<tr><td>" + key + "</td>\n<td>" +
data[0] + "</td>" + data[1] + "</tr>\n";
}
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}

Related

Can I displaying the same array after adding and removing items using vanilla JS and HTML without using a separate page or refreshing it?

I have this mini CRUD in vanilla JS and HTML.
I need to be able to add or remove items and then list the array movies accordingly. I also need to do that without refreshing the page because of my hardcoded array.
I can't really call listMovies() every time a title is added or removed , otherwise I'd have multiple repetitions of the array displayed in the page.
Can anyone help me with a a solution for that?
This is my code:
window.onload = function () {
//Hard-coded array of movies - data.
// App is not connected to a database so everytime page is refreshed the array goes back to its original content.
var movies = [
'The Shawshank Redemption', 'The Godfather', 'Star Wars: Episode V - The Empire Strikes Back',
'Forrest Gump', 'The Perks of Being a Wallflower', 'The Dark Knight', 'Changeling', 'It\'s a Wonderful Life',
'The Silence of the Lambs', '8 Mile', 'The Breakfast Club', 'Django Unchained', 'Silver Linings Playbook',
'The Shining', 'Seven', 'American Beauty', 'Pulp Fiction', 'Zero Dark Thirty', 'Argo', 'The Hurt Locker'
];
// Variables for DOM manipulation
// var movieList = document.getElementById("movie-list__container");
var videoInput = document.getElementById("videoInput");
var addVideo = document.getElementById("addVideo");
var removeVideo = document.getElementById("removeVideo");
var alertMsg = document.getElementById("alertMsg");
var autocomplete = document.getElementById("autocomplete");
var searchResults = document.getElementById("search-results");
var movieListResults = document.getElementById("movie-list-results");
listMovies();
function listMovies() {
movies.sort();
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
}
addVideo.onclick = addMovies;
function addMovies() {
var title = videoInput.value;
if (add(movies, title)) {
videoInput.value = "";
searchResults.innerHTML = '';
movieListResults.innerHTML += "<li>" + title + "</li>";
alertMsg.classList.remove("fail");
alertMsg.classList.add("success");
alertMsg.innerHTML = "Title was inserted successfully";
} else {
alertMsg.innerText = 'Please add a video title';
alertMsg.classList.remove("success");
alertMsg.classList.add("fail");
}
}
function add(data, title) {
if (title == "") {
return false;
} else {
data.push(title);
return true;
}
}
autocomplete.onkeyup = function () {
var results = [];
var userInput = this.value;
searchResults.innerHTML = "";
if (userInput != "") {
results = search(movies, userInput);
searchResults.style.display = "block";
if (results.length == 0) {
searchResults.innerHTML += "<li>Not found</li>";
searchResults.style.color = "grey";
} else {
searchResults.style.color = "black";
for (i = 0; i < results.length; i++) {
searchResults.innerHTML += "<li>" + results[i] + "</li>";
}
}
}
};
function search(data, input) {
var results = [];
for (i = 0; i < data.length; i++) {
if (input.toLowerCase() === data[i].slice(0, input.length).toLowerCase()) {
results.push(data[i]);
}
}
return results;
}
removeVideo.onclick = deleteMovie;
function deleteMovie() {
var title = videoInput.value;
if (title === "") {
alertMsg.innerHTML = 'Please enter the title you want to remove';
alertMsg.classList.add("fail");
} else {
if (remove(movies, title)) {
alertMsg.innerHTML = "Title has been successfully removed";
alertMsg.classList.add("success");
} else {
alertMsg.innerHTML = "Title not found";
alertMsg.classList.add("fail");
}
}
}
function remove(data, title) {
for (var i = 0; i < data.length; i++) {
if (title.toLowerCase() === data[i].toLowerCase()) {
data.splice(i, 1);
return true;
}
}
return false;
}
}; //End of window.onload
Nvm!
I figured it out by getting rid of the listMovies() and having the array printed once.
After that, I used a for loop for addMovie() and deleteMovie() to loop through the array and print it after the updates.
I realized that all I needed was to loop through the movies array and display the array again for both addMovie() and deleteMovie().
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
My logic to add and remove titles in JS was correct but the logic to display the titles in HTML wasn't.
PS: FYI I'm a beginner!
Cheers

Tableau Javascript API

Can you explain the functions below:
viz = new tableau.Viz(containerDiv, url, options);
function listenToMarksSelection() {
viz.addEventListener(tableau.TableauEventName.MARKS_SELECTION, onMarksSelection);
}
function onMarksSelection(marksEvent) {
return marksEvent.getMarksAsync().then(reportSelectedMarks);
}
function reportSelectedMarks(marks) {
var html = "";
for (var markIndex = 0; markIndex < marks.length; markIndex++) {
var pairs = marks[markIndex].getPairs();
html += "<b>Mark " + markIndex + ":</b><ul>";
for (var pairIndex = 0; pairIndex < pairs.length; pairIndex++) {
var pair = pairs[pairIndex];
html += "<li><b>Field Name:</b> " + pair.fieldName;
html += "<br/><b>Value:</b> " + pair.formattedValue + "</li>";
}
}
}
This function just listen the selected mark
This one throw the selection in reportSelectedMarks
It take the marks and write it in an HTML file in a '<'li'>'.
The fieldname would probably be a String and in the value it depend what you are workin with.
So basically these functions would be useful to dynamically print a selected mark on a graph or something like that and print a fielname and a value for that one.

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

How can get only the last element from an array javascript

I'm trying to get the only last visited page by the user, it should update on every page. I tried to save the URL in session cookie from there I'm retrieving the last visited page.
This is my code:
function getSecondCookie(cSname) {
var name = cSname + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
return "";
}
function checkHistory(targetId) {
var history = getSecondCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
for ( var i = sp.length - 1; i >= 0; i--) {
htmlContent += '<a class="previous_url" href="'
+ sp[i]
+ '">'
+ sp[i].substring(sp[i].lastIndexOf('/') + 1) + '</a><br>';
if (sp[i] == document.URL) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
console.log(sp[i]);
}
if (insert) {
sp.push(document.URL);
}
setSecondCookie("history", sp.toString(), 30);
} else {
var stack = new Array();
stack.push(document.URL);
setSecondCookie("history", stack.toString(), 30);
}
}
This is working fine how it has to.
At the moment it is showing like this:
https://www.example.com,https://www.example.com/about.html
and so on.
But I want here show only last element from an array. How can I do this?
let lastItem = array[array.length-1];
You can also do:
const last = array.slice(-1)[0]

How do I get object data from my json in my select?

So I have a select element and I am appending the data I am getting back from my API.
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1) {
$.getJSON("http://localhost:9000/api/helmets", function (key, value) {
console.log("request helmets");
var item = "";
headitemData = key;
var len = key.length;
for (let i = 0; i < len; i++) {
item += '<option value="' + key + '">' + key[i].Name + '</option>';
}
$('#itemSelect').append(item);
});
}
else {
clearIndex(headitemData);
}
}
That right there returns this
Which is just what I want.
But if I want to get other data like.. the Icon
Let's say I want to log to the console when I select a item from the Select element, how would I do that?
The end goal is to print out the Icon property of the json object when I change item in the Select.
JsonData example
<ItemModel>
<ACrush>+0</ACrush>
<AMagic>-5</AMagic>
<ARange>-2</ARange>
<ASlash>+0</ASlash>
<AStab>+0</AStab>
<DCrush>+43</DCrush>
<DMagic>-3</DMagic>
<DRange>+48</DRange>
<DSlash>+49</DSlash>
<DStab>+47</DStab>
<Icon>
https://vignette.wikia.nocookie.net/2007scape/images/a/a0/3rd_age_full_helmet.png/revision/latest?cb=20141217224936
</Icon>
<MagicDamage>+0%</MagicDamage>
<MeleeStrength>+0</MeleeStrength>
<Name>3rd age full helmet</Name>
<Prayer>+0</Prayer>
<RangedStrength>+0</RangedStrength>
<Slayer>0</Slayer>
<Undead>0</Undead>
</ItemModel>
You can set a data for your option like:
'<option data-icon="'+ key[i].Icon +'"></option>'
And then you can bind a change for your select after create your list:
$('select').on('change', function () {
const _this = $(this).find(':selected');
const icon = _this.attr('data-icon');
console.log(icon);
})
Since you want to use the data in other areas of your code, use a closure to create an environment where your variables don't leak out into the global space. For example, with the callback:
(function () {
var myData;
function test(callback) {
$.getJSON("http://localhost:9000/api/helmets",function (data) {
callback(data);
});
}
test(function (data) {
myData = data;
});
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1){
console.log("request helmets");
var item = "";
headitemData = myData;
var len = myData.length;
for (let i = 0; i < len; i++) {
item += '<option value="' +myData+ '">' + myData[i].Name + '</option>';
}
$('#itemSelect').append(item);
}
else {
clearIndex(headitemData);
}
}
$("#itemSelect").on("change",function(){
var value = $(this).val();
var newData = myData.filter(item=>{
if(myData.Name==value){
return item;
}
});
console.log(newData.Icon);
});
myData is cached as a global variable specific to that closure. Note the other functions will only be able to use that variable once the callback has completed.
Modified version below:
function getHeadData() {
$("#itemSelect").empty();
if (headitemData.length < 1) {
$.getJSON("http://localhost:9000/api/helmets", function (key, value) {
console.log("request helmets");
var item = "";
headitemData = key;
var len = key.length;
for (let i = 0; i < len; i++) {
var icon=key[i].Icon;
item += '<option data-icon="'+icon+'" value="' + key + '">' + key[i].Name + '</option>';
}
$('#itemSelect').append(item);
});
}
else {
clearIndex(headitemData);
}
}
Simple test to get the Icon from the first option in select:
//Get first option to test output
var test=$("#itemselect option:first");
//Read data-icon
console.log(test.data('icon'));
//To update data-icon
test.data('icon','new icon');
To echo when select is changed
$("#itemselect").change(function(e) {
var optionSelected = $("option:selected", this);
console.log (optionSelected.data('icon'));
});

Categories