Recover displayed JSON data from webpage? - javascript

I have made a webpage on JSFiddle that can display a simple JSON string. I plan on implementing ways to add/edit/remove keys and values, which is what the buttons on the right are for. Before adding all that, how do I go from this webpage representation back to a JSON string with the same formating when I click 'Save'?
Do I need to tag each element specifically some how and do a forEach(element) and extract the text value and then..?
Code on JSFiddle
<script>
var new_json = {"RegEx":{}}
var keys = document.getElementsByClassName("json_header")
for (key in keys){
//Somehow extract key value that is displayed, add to new_json as a key.
// for each key, need to add each value.
for (value in values){?}
}
Somehow I need to know which values belong to which key, is this possible with parent/child associaton?
In the JSFiddle, I append all the values as children to the key value
New to HTML and Javascript, any other suggestions are welcome.
Thank you!

Related

input value issues in javascript

I hav a google published csv sheet. I created a html table and want to display csv values from published csv sheet into all input fields inside html table.
due to a unspecified reason this question has been moved.
You can use Split() function https://www.w3schools.com/jsref/jsref_split.asp
let splitedResult = xmlhttp.responseText.split("\r");
You can assign the values to
element.value = splitedResult[0].trim();
element1.value = splitedResult[1].trim();
Check out this link for the implementation https://jsfiddle.net/SyamKumarD/xa49vspy/29/
I would suggest you to provide a iterable id to your table elements, so you don't need to hardcode the index to your split result and you can iterate through the element and assign the split value dynamically.

how to remove last value localstorage?

I want to ask you something guys, I hope you can help. I am confused how to remove last value from localstorage? the localstorage value I have as below, I want to delete the 'Sprints' value. If i use localStorage.removeItem('tags'), all values ​​will be deleted right? but I just want remove the last value. please help me, cause i'm confused
localStorage is only capable of storing string values so what you've got there is an array, serialised to JSON.
To remove elements from it, you'll need to
Parse the string as JSON to an array
Remove the item
Stringify the array and put it back in localStorage
const tags = JSON.parse(localStorage.tags ?? "[]")
localStorage.tags = JSON.stringify(tags.slice(0, -1))
You can of course single-line this
localStorage.tags = JSON.stringify(JSON.parse(localStorage.tags ?? "[]").slice(0, -1))

Looping through array to store string values in objects in localStorage and retrieving them

I'm building a web app that lets the user curate a double-feature film showing. The user enters a title, a blurb, and two film titles. On a submit button a function is called that displays the user-submitted title, user-submitted blurb, and makes two separate API calls to retrieve movie information on each respective feature.
I'm trying to establish something of a favorites functionality that utilizes localStorage. Conceptualizing the solution, let alone implementing it may be my first mistake, so I'm open to alternative suggestions, but I believe the best way to do this is to capture each search field value (title, blurb, movie_1, movie_2), store these four string values in an object and then push that object to an array, placing each object into localStorage and then getting each object from localStorage later on with a button click.
I'm able to capture these items, store them in localStorage and dynamically generate buttons that when clicked populates the four search field values back into the respective search fields, allowing the user to click the submit button again which runs the api calls and displays all of the content (again: title, blurb, movie_1, movie_2).
My problem is looping through the objects and grabbing the different search field data values. I suppose the problem is in assigning a name or key to the different objects that I'm looping through in the array and then accessing the correct values from the appropriate button through localStorage. I seem to be setting the same localStorage object (or rewriting it) and accessing it over and over, as opposed to setting a new localStorage object and getItem'ing the right one.
I'll provide some code snippets below, but it might be easier to peruse my GitHub repo: https://github.com/mchellagnarls/double_feature
If you look at the repo, latest code is found in index_test.html and app_test.js, whereas a previous version without any of the broken favorite functionality is found in index.html and app.js.
Some code snippets:
// logic to capture search field values and to eventually display them as buttons
// empty array
var dfArray = [];
// object to hold each of the string values to populate the search fields
var doubleFeature = {
feature_1: movie_1,
feature_2: movie_2,
DFTitle: title,
DFBlurb: blurb
}
dfArray.push(doubleFeature);
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var savedDF = JSON.parse(localStorage.getItem("df"));
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})
Thanks for any help. I'm learning web development and I may be overcomplicating things or missing out on an easier way to think about it and/or solve it.
Instead of this loop:
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
I would place the whole array into local storage
localStorage.setItem("df", JSON.stringify(dfArray));
Also then you have to decide which object to get from array in click function
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var id = -1; // which one
var savedDF = (JSON.parse(localStorage.getItem("df")) || []).find(pr => pr.id === id);
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})

Storing multiple ID's in localStorage using JavaScript

I am wanting to add a favorites function for my website. The technologies I am using are html, css, javascript and json. I am loading the json file thru ajax. A user is able to search for a device and add that device to their favourites and that is done via sessionStorage and localStorage, but my problem is when a user clicks on a new phone to add to their favorite, it overrides it. Do I have to put like an IF statement which will say if there is an id there still add this one. I am confused on how to do this...
Code Samples....
$(document).on('click', '.productfavourite', function(event) {
// whichever HTML element has been clicked,
// grab the id of that and set it as product fave
productFave = event.target.id;
localStorage.setItem('productFave', productFave);
console.log(productFave);
window.location="favourites.html";
});
I would suggest you save the selected items in an object or array before you write it in to the localStorage. After that you convert the object or array to a json string.
var selected = [];
$(document).on('click', '.productfavourite', function(event) {
selected.push(event.target.id);
console.log(selected);
});
this returns an array that your can convert to json.
Hope this helps.
So what you need is to keep a collection (list or dictionary) containing the favorites. I'll give you some examples, then you can figure out the rest.
You get the current productFav in your localStorage as follows:
var fav = localStorage.getItem("productFav") || [];
Now you don't want to store one value in localStorage, you want your whole list there. So you add the new favorites to the list and serialize the result as a json string
fav.push(newItem);
localstorage.setitem("productfav", JSON.stringify(fav));
I assumed fav is a list. It's best to use a dictionary if you want to avoid adding duplicated entries
You can also try:
if(Storage !== "undefined") {
localStorage.setItem("productFave", localStorage.getItem("productFave")+ ", newItemValue3");
}

how to access json data attribute

I have a data-attribute for several element that I'm using to store an ID and a value for each picklist values for each element. These will all be used to populate one field in a modal if one of the elements is edited.
I've added the ID and name for each option for each element into the data attribute like so:
{id:a0Dd000000RT1dOEAT,name:aa},{id:a0Dd000000RT1dPEAT,name:bb}, {id:a0Dd000000RT1dQEAT,name:cc},{id:a0Dd000000RT1dREAT,name:dd},{id:a0Dd000000RT1dSEAT,name:ee}
These represents 5 picklist options for one of the elements.
What is the syntax to extract each one? I've tried versions of:
$('#elementID').data('picklistvalues')[0].id
and its not working, any suggestions? I'm obviously far from a javascript expert.
You need to JSON.parse() the value that .data() returns; then you can work with the value as a full JavaScript object.
var data = $('#elementID').data('picklistvalues');
// the attr value in the OP is not quite valid JSON
var obj = JSON.parse('[' + data + ']');
var id = obj[0].id;
It looks to me that you need to place quotes around the "id" values. These are not quite numbers and will not likely parse as anything but strings.

Categories

Resources