Parse, how to save Appended text - javascript

Let's say I have the following code:
$('.button').click(function() {
$('body').append("<p>Random Text</p>");
});
Where when the .button is clicked, text is appended to the body.
How would I go about saving that text and having it always appear when the user visits the page.
Would it be wise to store it in a variable and then send it to Data Browser under
POST or another Class?
Hope this isn't too confusing, thanks!

This isn't ideal but without creating a server side or clientside db this would be a quick fix. If the user switches browsers or clears their cache the storage is gone.
http://jsfiddle.net/4gseg96g/1/
$(document).ready(function() {
// Read localStorage.
function getStorage() {
var obj = localStorage.getItem('objName');
if(!obj) {
obj = '';
}
return obj;
}
// Append localStorage obj, if any.
$('body').append(getStorage());
$('.button').click(function() {
console.log('click');
var str = "<p>Random Text</p>";
$('body').append(str);
var d = getStorage();
d += str;
console.log(d);
localStorage.setItem('objName', d);
});
});

Related

Set cookies using js-cookies to array

newbie here regarding Javascript. I am following this thread to set cookies to array by clicking button. Product compare session. Its working but the problem is, when i reload or open new page, when i click the button on new page or refreshed page, the cookies doesn't add new value, it replace all cookies which has been set from previous page. Here is the script.
`
cookie_data_load = Cookies.get('compare_data');
$('.view__compare').attr("href", "https://shop.local/compare/?id=" + cookie_data_load);
var fieldArray = [];
$( ".product__actions-item--compare" ).click(function(){
fieldArray.push($(this).data("compare"));
var unique=fieldArray.filter(function(itm,i){
return i==fieldArray.indexOf(itm);
});
var str = unique.join('-');
Cookies.set('compare_data', str, { expires: 7, path: '/' });
cookie_data = Cookies.get('compare_data');
console.log(str);
console.log(unique);
alert(unique);
$('.view__compare').attr("href", "https://shop.local/compare/?id=" + cookie_data);
return false;
});
`
And second question is how to limit the number of cookies value (array) from above code? Many thanks
I have read the js-cookies github but cant understand single thing.
*** Updated code from https://stackoverflow.com/users/8422082/uladzimir
`
var fieldArray = (Cookies.get('compare_data') || '').split('-');
$(".product__actions-item--compare").click(function () { if
(fieldArray.length >= 3) {
alert("unfortunately limit exceeded :("); } else {
fieldArray.push($(this).data("compare"));
var unique = fieldArray.filter(function (itm, i) {
return i == fieldArray.indexOf(itm);
});
var str = unique.join('-');
Cookies.set("compare_data", str, { expires: 7, path: "/" });
cookie_data = Cookies.get("compare_data");
console.log(str);
console.log(unique);
alert(unique);
$(".view__compare").attr(
"href",
"https://shop.local/compare/?id=" + cookie_data
);
return false; } });
`
Ivan, whenever you reload a page, the array of data "fieldArray" is ALWAYS empty (despite there is data in "compare_data" cookie from previous browser session)
What you have to do is to initialize "fieldArray" with it's initial value taken from cookie:
var fieldArray = (Cookies.get('compare_data') || '').split('-')
Cookie stores string data with maximum size of 4kb. More over, cookie have no idea, if it stores serialized array, object, or anything else... It just keeps a string of text and that's it. So (as far as I know), there is no way to limit array length using cookie settings.
So, the only workaround here is to do this length-check programmatically, like following:
$('.product__actions-item--compare').click(function () {
if (fieldArray.length >= 3) {
alert('unfortunately limit exceeded :(');
} else {
// do your actions
}
});

Take selected text, send it over to Scryfall API, then take the link and put it in the selected text

I've been able to sort out the middle bit (the API seems to be called to just fine) along with the submenu displaying. Originally I thought that just the end part wasn't working but I'm now thinking that the selection part isn't either.
What am I doing wrong with the getSelection() and what do I need to do to insert a link into said selection? (to clarify, not to replace the text with a link, but to insert a link into the text)
//Open trigger to get menu
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Scry', 'serumVisions')
.addToUi();
}
//Installation trigger
function onInstall(e) {
onOpen(e);
}
//I'm not sure if I need to do this but in case; declare var elements first
var elements
// Get selected text (not working)
function getSelectedText() {
const selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
Logger.log(elements);
} else {
var elements = "Lack of selection"
Logger.log("Lack of selection");
}
}
//Test run
// insert here
// Search Function
function searchFunction(nameTag) {
// API call + inserted Value
let URL = "https://api.scryfall.com/cards/named?exact=" + nameTag;
// Grabbing response
let response = UrlFetchApp.fetch(URL, {muteHttpExceptions: true});
let json = response.getContentText();
// Translation
let data = JSON.parse(json);
// Jackpot
let link = data.scryfall_uri;
// Output
Logger.log(link);
}
// Test run
searchFunction("Lightning Bolt");
//Let's hope this works how I think it works
function serumVisions() {
const hostText = getSelectedText();
const linkage = searchFunction(hostText);
// Unsure what class I'm supposed to use, this doesn't
const insertLink = DocumentApp.getActiveDocument().getSelection().newRichTextValue()
.setLinkUrl(linkage);
Logger.log(linkage);
}
For the first part, I tried the getSelection() and getCursor() examples from the Google documentation but they don't seem to work, they all just keep returning null.
For the inserting link bit, I read all those classes from the Spreadsheet section of the documentation, at the time I was unaware but now knowing, I haven't been able to find a version of the same task for Google Docs. Maybe it works but I'm writing it wrong as well, idk.
Modification points:
In your script, the functions of getSelectedText() and searchFunction(nameTag) return no values. I think that this might be the reason for your current issue of they all just keep returning null..
elements of var elements = selection.getRangeElements(); is not text data.
DocumentApp.getActiveDocument().getSelection() has no method of newRichTextValue().
In the case of searchFunction("Lightning Bolt");, when the script is run, this function is always run. Please be careful about this.
When these points are reflected in your script, how about the following modification?
Modified script:
Please remove searchFunction("Lightning Bolt");. And, in this case, var elements is not used. Please be careful about this.
From your script, I guessed that in your situation, you might have wanted to run serumVisions(). And also, I thought that you might have wanted to run the individual function. So, I modified your script as follows.
function getSelectedText() {
const selection = DocumentApp.getActiveDocument().getSelection();
var text = "";
if (selection) {
text = selection.getRangeElements()[0].getElement().asText().getText().trim();
Logger.log(text);
} else {
text = "Lack of selection"
Logger.log("Lack of selection");
}
return text;
}
function searchFunction(nameTag) {
let URL = "https://api.scryfall.com/cards/named?exact=" + encodeURIComponent(nameTag);
let response = UrlFetchApp.fetch(URL, { muteHttpExceptions: true });
let json = response.getContentText();
let data = JSON.parse(json);
let link = data.scryfall_uri;
Logger.log(link);
return link;
}
// Please run this function.
function serumVisions() {
const hostText = getSelectedText();
const linkage = searchFunction(hostText);
if (linkage) {
Logger.log(linkage);
DocumentApp.getActiveDocument().getSelection().getRangeElements()[0].getElement().asText().editAsText().setLinkUrl(linkage);
}
}
When you select the text of "Lightning Bolt" in the Google Document and run the function serumVisions(), the text of Lightning Bolt is retrieved, and the URL like https://scryfall.com/card/2x2/117/lightning-bolt?utm_source=api is retrieved. And, this link is set to the selected text of "Lightning Bolt".
Reference:
getSelection()

Table contents disappear on refresh

I'm trying to make a money tracker but every time I refresh they disappear. Anyone know how I can use local storage to make them stay? I've tried using local storage but I can't wrap my head around it and it is very confusing for me. Code Pen - https://codepen.io/jordandevelops/pen/wvPWzxL
const table = document.getElementById('contentTable'),
inputText = document.getElementById('inputText'),
inputPrice = document.getElementById('inputPrice'),
inputDate = document.getElementById('inputDate'),
form = document.getElementById('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
addNewItem();
});
function addNewItem(){
if(inputPrice.value == ''){
alert('Error, please enter price of purchase.');
return;
}
if(inputDate.value == ''){
alert('Error, please enter date of purchase.');
return;
}
let newTr = document.createElement('tr');
let newTd1 = document.createElement('td');
let newTd2 = document.createElement('td');
let newTd3 = document.createElement('td');
table.appendChild(newTr);
newTr.appendChild(newTd1);
newTr.appendChild(newTd2);
newTr.appendChild(newTd3);
newTr.classList.add('createdTr')
newTd1.classList.add('tdName');
newTd2.classList.add('tdPrice');
newTd3.classList.add('tdDate');
newTd1.innerText = inputText.value;
newTd2.innerText = `$${inputPrice.value}`;
newTd3.innerText = inputDate.value;
}
In local storage, you store the data structure in JSON format (not the HTML that contains the data).
To store data:
function addNewItem(){
//... check and validate the input like you do
// grab the current local storage or create an empty container
let theData = localStorage.get('theData') || "[]";
theData = JSON.parse(theData); // get it into object format
//add to it
theData.push({text: inputText.value, price: inputPrice.value, date: inputDate.value});
// store that back into local storage as a string
localStorage.set('theData', JSON.stringify(theData));
//... continue on with your code
To retrieve the data, do it on page load
document.addEventListener('DOMContentLoaded', () => {
let theData = localStorage.get('theData') || "[]";
JSON.parse(theData).forEach(d => {
// ... this is where you take the existing local storage list and populate it into your HTML.
// You can leverage your existing addNewItem function but you'll need to update it to allow for sending input directly into it.
})
Local storage can work ok, but I'd recommend using IndexedDB if you want to store data like this.
IndexedDB is even more complicated than local storage in some ways, but there's a great library called "Dexie" that makes it a lot easier. You can see it here: https://dexie.org/
Using Dexie, you can save, restore and query your data. It will take a little time to experiment with and learn how to do, but it will be a great tool to have in your toolbox.

Pass JS variable from one page to other

I created AJAX auto-complete from a JSON file
function run() {
field.show();
field.html('');
let val = search.val();
let input = new RegExp(val, "gi");
$.get("js/pk.json").then(function(city) {
if (val.trim().length === 0) {
field.empty();
field.hide();
}
$.each(city, function(key, value) {
let n = new RegExp(val, 'gi');
let name = value.city.replace(n, `<span class="me">${val}</span>`);
if (value.city.search(input) != -1) {
field.append(`<li class="list-search" data-name='${value.city}'>${name} ${value.country}<br><br></li>`);
}
})
})
});
and I want to pass "data-name" attribute clicked li tag value to div in another page.
That is :
$("#field").on("click", "li", function(e) {
finalName=$(this).attr('data-name');
});
and the div is <div class="Fname"></div>.
The variable finalName is global but it shows undefined outside this click event.
I am not an expert but I think that is due to AJAX Asynchronous request which loads variable before it is assigned value. Can anyone please explain to me how it will work? I found other answers that were related to this but couldn't understand them. Thank you in advance
You can do this by saving you data in localStorage o sessionStorage and then retrieve it in the other page. For example:
sessionStorage.setItem(SOME_KEY, VALUE_YOU_WANT_TO_SAVE);
and in the other page just retrieve it by calling:
var data = sessionStorage.getItem("THE_SAME_KEY_USED_BEFORE");
Now, data is has the data you were trying to pass.
I hope this help!

HTML5 local storage not saving between page refreshes

I am using HTML5 local storage for the first time using FF5. I have the below javascript, it should save a string into local storage, however when the page is reloaded there isn't any values in local storage. What am I doing wrong? Why is 'foo' not populated on the pages sedond load?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js</script>
<script>
$(document).ready(function() {
if (!localStorage) {return false; }
var foo = localStorage.getItem("key1");
if (foo != null)
{
document.getByName("identifier").value = foo;
}
localStorage["key1"] = "value1";
});
</script>
You should use localStorage.setItem. For example
localStorage.setItem("key1", "value1");
NOTE: IE 7 does not have localStorage support
I've also had this same issue. I've discovered that I am unable to retrieve items from local storage during the document.ready, but I am able to get the items afterwards.
I believe you need to use the "setItem" method, i.e.:
localStorage.setItem('key1', 'value1');
Have a look at my code
You do not need getItem and setItem
jQuery('.close-intro').click(function() {
window.localStorage['intro'] = 1;
jQuery('.intro-holder').slideUp();
jQuery('.open-intro').show();
});
jQuery('.open-intro').click(function() {
window.localStorage['intro'] = 0;
jQuery('.intro-holder').slideDown();
jQuery(this).hide();
});
var opcl = window.localStorage['intro'];
if (opcl == 1) {
jQuery('.intro-holder').slideUp();
jQuery('.open-intro').show();
}
if (opcl == 0) {
jQuery('.intro-holder').slideDown();
jQuery('.open-intro').hide();
}

Categories