js: hand generated text to next site - javascript

i use this js code to generate text:
let green, display, button, clock, end;
green = ["x", "t", "g", "l"];
display = ["l", "h", "r", "e"];
button = ["e", "D", "l", "w"];
clock = ["o", "b", "a.", "e"];
end = ["T", "g", "t", "w"];
function randGen() {
return Math.floor(Math.random() * 4);
}
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
document.getElementById('sentence').innerHTML = """ + content + """;
};
sentence();
and put it in html like this:
<button style="" onclick="sentence()">generate text<i class="fa fa-refresh" aria-hidden="true"></i></button>
<div class="container">
<p id="sentence"></p>
</div>
Now i want to use the generated text the user generates by hitting the "generate text"-button on another html-document. Is it possible? Do i need to safe this text anywhere before using it on another html-document?
thanks in advance
John

You can use localStorage to solve your problem.
Save your sentence to localStorage like this:
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
return content;
};
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", sentence());
}
And get sentence value on another page like this:
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("sentence");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
</script>
Hopefully, it will help your problem. Please let me know if you have any issues.

Related

js: Show text saved in localStorage on same page

I'm a total beginner in javascript and spend too much time trying to get this working.
What I want to do:
1.html generates sentences from different arrays. So the user can push the button "generate" and the arrays will combine randomly, as long as there is a sentence he/she likes. I need this generated sentence on 2.html. I used localStorage to store the generated sentence. The thing I want to get working is, that the generated sentence on 1.html is also shown on 1.html after the User pushes the "generate" button. Never got it working properly.
I replaced the words of the sentences with letters for now.
Here the code of 1.html
let green, display, button, clock, end;
green = ["a", "d", "d", "v"];
display = ["f", "g", "v", "h"];
button = ["h", "r", "h", "h"];
clock = ["h", "t", "c", "r"];
end = ["g", "t", "x", "r"];
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
return content;
}
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", sentence());
}
<h1>Generator</h1>
<button onclick="sentence()">generate</button>
This is 2.html
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("sentence");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
</script>
The function sentence() does not by itself save to localStorage. It only generates a new sentence each time it's called. You can change as follows:
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", content);
}
const message = document.querySelector('.message');
message.innerText = content;
}
And in 1.html add this:
<div class="message"></div>

reset var to blank after running loop in javascript

HELP! I have been banging my head against the wall for hours and hour trying to find a way that once my "game" has ended either by winning or losing my lettersGuessed var resets and no longer displays my userGuesses. I can get through the first loop/ round by setting lettersGuessed = ""; but when a new userGuess is entered, I get an uncaught type error that lettersGuessed is not a function.
// array of letters for the computer to chose from
var letterBank = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
var lettersGuessed = []
// variables starting value for tally counter
var wins = 0;
var losses = 0;
var guessesLeft = 6;
var compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
for (var i = 0; i <= guessesLeft; i++) {
document.onkeyup = function(event) {
// var for use of collecting key answers for both user and computer.
var userGuess = event.key;
lettersGuessed.push(userGuess);
// if statements to get a win or loss
if (userGuess === compGuess) {
guessesLeft = 7;
alert("You won!")
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
userGuess = "";
lettersGuessed = "";
wins++;
}
if (userGuess != compGuess) {
guessesLeft--;
}
if (guessesLeft === 0) {
alert("GAME OVER");
guessesLeft = 6;
losses++;
userGuess = "";
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
}
// variables to display a win/loss tally and the computer/user guesses
var html =
"<p> your choice: " + userGuess + "</p>" +
"<p> losses: " + losses + "</p>" +
"<p> wins: " + wins + "</p>" +
"<p> Guesses left: " + guessesLeft + "</p>" +
"<p> Your Guesses so far:" + lettersGuessed + "</p>";
// sends info collected from html var to the game div
document.querySelector("#game").innerHTML = html;
};
};
<div id="game">Type a letter</div>
lettersGuessed is an array when declared and not a string. To reset, you need to use the same code as the first initialization. So in your first if statement, replace
lettersGuessed = "";
with
lettersGuessed = [];

How to get unlimited characters in a personal encryption on Javascript

Recently, I have been working on an piece of code that encrypts letters and decrypts them as long as the user has the proper, custom key. I worked out how to do it, but for every letter I want to add, I have to put:
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
Then at the end:
var encrypted = (_1 + _2 + _3 + _4 + _5 + _6 + _7 + _8 + _9 + _10 + _11 + _12 + _13 + _14 + _15 + _16 + _17 + _18 + _19 + _20 + _21 + _22 + _23 + _24 + _25 + _26 + _27 + _28 + _29 + _30 + _31 + _32 + _33 + _34 + _35 + _36 + _37 + _38 + _39 + _40 + _41 + _42 + _43 + _44 + _45 + _46 + _47 + _48 + _49 + _50 + _51 + _52 + _53 + _54)
For however many letters I put in.
A simplified version of the code with only 3 letters is this:
var map = {
"a" : "A",
"b" : "B",
"c" : "C",
"d" : "D",
"e" : "E",
"f" : "F",
"g" : "G",
"h" : "H",
"i" : "I",
"j" : "J",
"k" : "K",
"l" : "L",
"m" : "M",
"n" : "N",
"o" : "O",
"p" : "P",
"q" : "Q",
"r" : "R",
"s" : "S",
"t" : "T",
"u" : "U",
"v" : "V",
"w" : "W",
"x" : "X",
"y" : "Y",
"z" : "Z",
" " : " "
}
function main()
{
var input = prompt("Enter a character!");
var encrypted = -1;
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
if ( map.hasOwnProperty(input[1]) )
{
var _2 = map[input[1]]
}
if ( map.hasOwnProperty(input[2]) )
{
var _3 = map[input[2]]
}
var encrypted = (_1 + _2 + _3)
document.write(encrypted);
}
main()
(The map is just for simplicity, as it is a little more complicated in the full code)
Is there a way to have access to as many letters as I want to simplify the code?
You can use a loop for this kind of thing. Here is an example:
var map = {" " : " "};
for(var i = 0; i < 25; i++){
map[String.fromCharCode(97 + i)] = String.fromCharCode(65 + i);
}
function main() {
var input = prompt("Enter a character!");
var encrypted = "";
for(var i = 0; i < input.length; i++){
if(map[input[i]]){
encrypted += map[input[i]];
}
}
document.write(encrypted);
}
main();

"Document is missing (perhaps it was deleted?)" in reference to a document that was just created

My script creates a document, stores the document url in a cell on the spreadsheet, then another function opens said document using that url. I am getting the "Document is missing" error about 70% of the time I attempt to run it. Any ideas? the failure is on line 52.
function resultsDoc() {
var ssa = SpreadsheetApp;
var ss = ssa.getActiveSpreadsheet();
var sheets = ss.getSheets();
var ui = ssa.getUi();
var doca = DocumentApp;
var drive = DriveApp;
var template = "1uSCtqPwDYM-AtGAu3kzv3ZD0jdXnl12GxmdF_BDNb-M";
var source = doca.openById(template);
var resDocCopy = drive.getFileById(template).makeCopy('Tournament Results');
var resDocId = resDocCopy.getId();
var resDoc = doca.openById(resDocId);
var docBody = resDoc.getBody();
var resDocUrl = resDoc.getUrl();
sheets.shift();
for (var dis in sheets) {
var thisSheet = sheets[dis];
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "f"];
var disLetter = letters[dis];
var eventa = thisSheet.getName();
var aOne = thisSheet.getRange('B3').getValue() + " " + thisSheet.getRange('A3').getValue();
var aTwo = thisSheet.getRange('B4').getValue() + " " + thisSheet.getRange('A4').getValue();
var aThree = thisSheet.getRange('B5').getValue() + " " + thisSheet.getRange('A5').getValue();
var aFour = thisSheet.getRange('B6').getValue() + " " + thisSheet.getRange('A6').getValue();
var aFive = thisSheet.getRange('B7').getValue() + " " + thisSheet.getRange('A7').getValue();
var aSix = thisSheet.getRange('B8').getValue() + " " + thisSheet.getRange('A8').getValue();
docBody.replaceText('<<' + disLetter + '>>', eventa);
docBody.replaceText('<<' + disLetter + '1>>', aOne);
docBody.replaceText('<<' + disLetter + '2>>', aTwo);
docBody.replaceText('<<' + disLetter + '3>>', aThree);
docBody.replaceText('<<' + disLetter + '4>>', aFour);
docBody.replaceText('<<' + disLetter + '5>>', aFive);
docBody.replaceText('<<' + disLetter + '6>>', aSix);
}
ss.insertSheet("Links");
var linksSheet = ss.getSheetByName("Links");
linksSheet.getRange(1, 1).setValue("Link to results page:");
linksSheet.getRange(2, 1).setValue(resDocUrl);
Utilities.sleep(9000);
}
function sweepsDoc() {
var doca = DocumentApp;
var linksSheet = ss.getSheetByName("Links");
var resDocUrl = linksSheet.getRange(2, 1).getValue();
var resDoc = doca.openByUrl(resDocUrl);
var docBody = resDoc.getBody();
var sweepsSheet = ss.getSheetByName('Sweeps');
docBody.replaceText("<<sweeps1>>", sweepsSheet.getRange('B2').getValue());
docBody.replaceText("<<sweeps2>>", sweepsSheet.getRange('B3').getValue());
docBody.replaceText("<<sweeps3>>", sweepsSheet.getRange('B4').getValue());
}
Alright - so I figured out a "workaround" more than an actual solution. Instead of storing and accessing the document Url, I switched over to using the document's Id.
While I still don't understand why the Url causes it to lose track of the document, using the Id has 100% success rate over 20 attempts, while using the Url only had a 10% success rate over 20.
If you know what the problem with using the Url is, please let me know. If you're having the same problem, switch your code to use the doc id.
I'm not 100% sure, but I think not saving the document could be causing the problem.
Add the line below to the end of your code that builds the doc.
resDoc.saveAndClose();

Using JS .split and join with an array multiple times. It only runs the last pair

I'm trying to use JS to parse a text input field on keyup, to show the same text with all the pronouns changed. It should read: I, me, mine and produce:
you, you, yours
s/he, s/he, hers/his
they, them, theirs
It works perfectly for the first set of replacements. On the second and third sets it only replaces the last variable set in the array. :(
I'm sure there is a more efficient way to write this code. I've made each section completely duplicative trying to solve my problem to no available. I fear I'm making a simple mistake.
Here's a fiddle if you'd like to take a pass at it.
http://jsfiddle.net/8k9b83mo/3/
Here's the raw JS:
function grammar() {
text = ' ' + document.getElementById("first_p").value + ' ';
var array = {
" my ": " your ",
" myself ": " yourself ",
" mine ": " yours ",
" I ": " you ",
" me ": " you ",
" our ": " your "
};
for (var val in array)
text = text.split(val).join(array[val]);
document.getElementById('2_pe').innerHTML = text;
text2 = ' ' + document.getElementById("first_p").value + ' ';
var array2 = {
" my ": " her/his ",
" myself ": " herself/himself ",
" mine ": " hers/his ",
" I ": " s/he ",
" me ": " s/he ",
" our ": " her/his "
};
for (var val2 in array2)
text_3pe1 = text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text_3pe1;
text3 = ' ' + document.getElementById("first_p").value + ' ';
var array3 = {
" my ": " their ",
" myself ": " themself ",
" mine ": " theirs ",
" I ": " they ",
" me ": " they ",
" our ": " their "
};
for (var val3 in array3)
text_3pe2 = text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text_3pe2;
}
Thanks so much for your help! I'm pulling my hair out on this one.
You aren't updating text2 and text3 each time through the for loop, so only the last changes are saved to text_3pe1 and text_3pe2. Replace text_3pe1 with text2 and text_3pe2 with text3, like this, and you should get the result you're looking for.
you are using the wrong variables in your forEach methods
change the following lines :
text_3pe1 = text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text_3pe1;
text_3pe2 = text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text_3pe2;
for
text2= text2.split(val2).join(array2[val2]);
document.getElementById('3_pe1').innerHTML = text2;
text3= text3.split(val3).join(array3[val3]);
document.getElementById('3_pe2').innerHTML = text3;
it was doing the substitutions, just in the wrong place.
here is the fiddle http://jsfiddle.net/ucpfL2bs/
As others have said you are not updating the correct variables in your for loops. However I think you should reconsider your approach a bit. Right now you're splitting and joining on every iteration of the loop which is a bit unnecessary.
This approach allows you to reduce your similar code and replaces the words in a temporary array and joins back once:
function grammar() {
replace(document.getElementById('first_p').value, {
"my": "your",
"myself": "yourself",
"mine": "yours",
"I": "you",
"me": "you",
"our": "your"
}, document.getElementById('2_pe'));
replace(document.getElementById('first_p').value, {
"my": "her/his",
"myself": "herself/himself",
"mine": "hers/his",
"I": "s/he",
"me": "s/he",
"our": "her/his"
}, document.getElementById('3_pe1'));
replace(document.getElementById('first_p').value, {
"my": "their",
"myself": "themself",
"mine": "theirs",
"I": "they",
"me": "they",
"our": "their"
}, document.getElementById('3_pe2'));
}
function replace(inputText, replacements, displayElement) {
var words = inputText.split(' ');
for (var i = 0; i < words.length; i++) {
var word = words[i];
if (replacements[word.trim()]) {
words[i] = replacements[word].trim();
}
}
displayElement.innerHTML = words.join(' ');
}
Updated JSFiddler

Categories

Resources