I would need some help to adjust this code to suit my needs.
I need to build a javascript that will be stored on a SharePoint page in order to generate on demand a NEW random USERID.
The problem is that I have zero knowledge of javascript, but I am very willing to learn.
The ID is built like this : "IT" & "number from 30001 to 79999"
Example: IT30002
The IDs created must always be different, so those "used" have to be permanently stored in a file.
Every time a new ID is prompted, the script will check the history file and provide a new ID.
Is there a way to achieve what I need?
I have looked at these 2 codes examples:
This example has the key functionality of storing the previous choices, so I am sure I will not use the same ID twice, the problem is that I need numbers, not names and also I need the script to store the numbers permanently
The code below has the other functionality of the "button" to press in order to display the ID.
<html>
<body>
<p id="one"></p>
<button onclick="random()">Random</button>
<script>
function random(){
document.getElementById("one").innerHTML = Math.floor(Math.random() * 10);
}
</script>
</body>
randojs.com makes this pretty easy.
Put this in the head of your page:
<script src="https://randojs.com/1.0.0.js"></script>
And then you can use this JavaScript:
var sequence = randoSequence(30001, 79999);
var currentIndex = 0;
function getNewID(){
return "IT" + sequence[currentIndex++];
}
And you can add this button to the body of your page if you need to:
<button onclick="alert(getNewID());">Alert new ID.</button>
Here's all of that together (click "Run" and then click the "Alert new ID." button that shows up to see it work):
var sequence = randoSequence(30001, 79999);
var currentIndex = 0;
function getNewID(){
return "IT" + sequence[currentIndex++];
}
<script src="https://randojs.com/1.0.0.js"></script>
<button onclick="alert(getNewID());">Alert new ID.</button>
Some references to concepts for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set and https://www.w3schools.com/jsref/prop_win_localstorage.asp
Well, all you need to do is generate a random number and store it somewhere. Since, you're using javascript at the front-end, you can't write onto a file without using some backend. If you're fine with storing things for a single user's session, you can use localstorage to store your previous findings in a Set. This lets you store stuff in the browser but for a single user only.
Now the question is what to store? Everytime you generate a random number, look for it in the set from localstorage. If it exists, generate the random number again and repeat lookup process. Keep repeating this random number generation and lookup process until a new random number is found.
What to do if a new random number is finally generated i.e. it doesn't exist in the set? You store it into the set and save the set to the localstorage, stop repeating the process and use the newly generated number for your needs.
That's it.
#Rishinder has explained some of your possible approaches. I will share some code to explain the same. This will print the random numbers on the browser
<html>
<body>
<div id="random"></div>
<button onclick="printRandom()">Generate numbers</button>
</body>
<script>
// fetch and prepare the data
var storage = localStorage.getItem('random'),
existingNumbers = storage ? JSON.parse(storage) : {};
// will generate the random number
function generateRandom() {
var loop = true,
newRand;
while (loop) {
newRand = Math.ceil(Math.random() * 1000000) % 79999;
if (existingNumbers[newRand])
continue;
else if (!existingNumbers[newRand] && newRand < 30001)
continue;
else if (!existingNumbers[newRand]) {
existingNumbers[newRand] = true;
localStorage.setItem('random', JSON.stringify(existingNumbers));
loop = false;
}
}
return Object.keys(existingNumbers).join(', ');
}
// print the existing numbers already stored
document.getElementById('random').innerHTML = Object.keys(existingNumbers).join(', ');
function printRandom() {
document.getElementById('random').innerHTML = generateRandom();
}
</script>
</html>
Hope this helps
Related
I am at starting web dev, already using html/css.
For a little project, I had a look at JavaScript. (My goal is that when people click a button, the site will show a random sentence that will be taken from a google sheet cell.)
Could you tell me please if it is even possible? If so, please share some ideas that I will explore. If not, please give me some alternative ideas... Thanks so much.
Have a good day!
-LeganV9
This is possible using Google Apps Script!
I have a working demo here, with the source being here. I dare you to get the jackpot. :D
In order to make this, you can go to https://script.new. Now, in code.gs put this:
function doGet() {
return HtmlService.createTemplateFromFile("index").evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getVals(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IDbhQhaImcQB-4j-iByajwAkvxkutptcPMhMTxNrPtU/edit#gid=0");//Put your URL here
var sheet = ss.getSheetByName("Sheet1");//Put your sheet name here
var AMOUNT_OF_SENTENCES = sheet.getMaxRows().toString().replace(".0","");//You can replace this with a number eg 20
var range = sheet.getRange(1, 1,AMOUNT_OF_SENTENCES);
var values = range.getValues();
var newValues = [];
for(var i = 1; i<values.length;i++){
if(values[i][0] === "" || values[i][0] === " "){
}else{
newValues.push(values[i][0]);
}
}
return {valuesVar: newValues };
}
After that, create a new HTML file called "index" and put this in it:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
The results are: <span id = "results">Loading...</span>
</h1>
<button id = "yourIdHere">Click me!!</button>
<script>
var yourDataList;
function onSuccess(data) {
yourDataList= data.valuesVar;
}
google.script.run.withSuccessHandler(onSuccess).getVals();
var myBtn = document.querySelector("#yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
document.querySelector("#results").innerText = getRandom(); //Do whatever you want to with the random value
});
document.querySelector("#results").innerText = getRandom();//Change from loading...
</script>
</body>
</html>
Welcome to the world of web development! Hope your project is a success.
It should definitely be possible, since Google Sheets offers an API which has read/write functionality (https://developers.google.com/sheets/api).
You could even later extend this so people can submit their own sentences, given that writing to a Google Sheet is also possible with this API.
However, since you're starting out, consider treating this as an iterative process. You don't have to publish your first version, but just to prevent overwhelming yourself, you might want to set small milestones along the way - each adding more functionality. For example:
Create an array of random sentences (you could, for example, start with using this to keep it simple: https://github.com/JamesFT/Database-Quotes-JSON).
Select and log a random sentence to the console (console.log()) each time the script is executed.
Transfer the random sentence to render in HTML and allow a new sentence to be generated each time a button is pressed.
Move your sentences into a Google Sheet and begin exploring the API.
This way, you achieve something in a much shorter space of time, while working towards your end goal. It's a good way to keep motivated and make things more manageable.
Best of luck!
I am trying to build a logic where we click a button and save an ID in localStorage. We could have 2 ids max. However, we can also remove an ID from it and add a new one. Finally, we cannot add more than 2 and these ids must be unique. These IDs will be then set as an input value in a form.
So I have four steps page:
Homepage page
Search result page
Single article page
Form result page
Each page has:
<form id="post_form_id" method="post" action="/test/compare/">
<input id="input_post_id" type="hidden" name="varPostId" value="">
<button type="submit" class="btn btn-link nav-link" id="jikubox"></i>
<span class="badge badge-secondary">0</span></button>
</form>
Saved IDs will be set in name="varPostId" value=""
Now the tricky part which is confusing me, so localStorage can only have strings so first of all on each page load I do:
var lines = localStorage.getItem("lines") ?
JSON.parse(localStorage.getItem("lines")) : [];
Then since in the article page I have a save button to add the current article id in the array, I do:
<button type="button" class="save_post">SAVE</button>
JS
$(".save_post").on("click", function(e) {
e.stopImmediatePropagation();
if (localStorage.getItem("attempts") >= 2) {
alert('nope');
return;
} else {
// Here I set the id for each article which I saved before via php in a span
var thisId = $(".my_post_id").attr("data-id");
var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : [];
lines.push(thisId);
localStorage.setItem("lines", JSON.stringify(lines));
console.log(lines);
$("#input_post_id").val(JSON.parse(localStorage.getItem("lines")));
var attempts = Number(localStorage.getItem("attempts"));
localStorage.setItem("attempts", ++attempts);
console.log(localStorage.getItem("attempts"));
$("#jikubox span").text(localStorage.getItem("attempts"));
}
});
Notice I have another localStorage: attempts, that is used to add or remove a number I set in a counter badge, basically an indicator which tells how many items I have in my "bag". Remember: max 2 and unique.
So finally on the form result page I have a button to remove added items and the following js is used:
$(".removeJiku").on("click", function(){
// Here I set the id for each article, I do that with php
// <span class="removeId" data-thisPostId="<?php echo $idThisPost; ?>"></span>
var removeThisId = $(".removeId").attr("data-thisPostId");
$(this).parent().fadeOut();
var attempts = Number(localStorage.getItem("attempts"));
localStorage.setItem("attempts", --attempts);
$("#jikubox span").text(localStorage.getItem("attempts"));
lines.splice($.inArray(removeThisId, lines), 1);
localStorage.getItem("lines", lines);
localStorage.setItem("lines", lines);
console.log(localStorage.getItem("lines"));
});
The logic is kinda ok but after I try few times, I eventually get empty lines array and the ids are not set to the input value. I think I over complicated the logic and I was wondering where and how I could simplify and correct it. I am looking into a single general bit of code which handles all of this without complicating the logic.
UPDATE
Thanks to an answer, one bit of code has been simplified and the counter will be set by checking the length of the ids in lines array so We can remove the whole code for the attempts local storage logic
$("#jikubox span").text(lines.length);
Assume you store your IDs in an array-
var idList=["123","456"];
You can store IDs like this -
localStorage.setItem("idList",JSON.stringify(idList));
and fetch idList like this-
JSON.parse(localStorage.getItem("idList")).length
Just make sure to put validations all around.
P.S. No need to count the "attempts" as you can anytime use the below code to find the length of the idList, which can be 2 or any number you want
JSON.parse(localStorage.getItem("idList")).length
UPDATE:
To remove IDs-
function removeId(array, element) {
const index = array.indexOf(element);
array.splice(index, 1);
}
Fetch array from localStorage and pass it into this function -
idList = JSON.parse(localStorage.getItem("idList"))
and call the function like this -
removeId(idList,idToBeDeleted)
This block isn't doing what you want:
lines.splice($.inArray(removeThisId, lines), 1);
localStorage.getItem("lines", lines);
localStorage.setItem("lines", lines);
The second line is getting something from localStorage but isn't doing anything with it. It could be the equivalent of
lines.splice($.inArray(removeThisId, lines), 1);
['one line', 'another line'];
localStorage.setItem("lines", lines);
Just some random value that proceeds to get ignored by the interpreter.
The other problem is that you're setting localStorage.lines to the plain lines variable, not to JSON.stringify(lines).
Note that you can simplify your syntax noise just by doing
localStorage.lines = JSON.stringify(lines);
and
const lines = JSON.parse(localStorage.lines || '[]');
localStorage.getItem('item') only accepts one parameter, which will return the value if it exists in the local storage and will return null item doesn't exist.
localStorage.setItem(item, value) accepts two parameters. item which is a key and the value which is to be saved for the key. If item is already set it will overwrite the value.
I want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.
Can someone help me with that?
function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";
var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
How about storing all random strings in an array, like so:
function switchText(){
var randomWords = ["hello", "there", "ObiWan"];
var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
document.getElementById("randomText").innerHTML = randomWords[randomIndex];
//the problem
}
Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to
document.getElementById("randomText").innerHTML = this['text' + randomNumber];
However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.
Store those texts into an array and use the random number.
Get the random number as follow: Math.floor(Math.random() * 3)
function switchText(){
var texts = ["hello", "there", "ObiWan"];
var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
You can store those texts into an object as well.
function switchText() {
var texts = {
"text1": "hello",
"text2": "there",
"text3": "ObiWan"
};
var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.
Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.
All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.
This structure and solution make your code simpler and more flexible.
Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.
var strings = ["hello","there","ObiWan"]; // Store the possible strings in an array
var btn = document.getElementById("randomText"); // Get a reference to the trigger element
var output = document.getElementById("output"); // And the output area
// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
// Set the output to a string from the array using a random index
output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>
I'm struggling with what seems to be a basic Javascript problem. I generate a unique key for Firebase but that unique key which I want to stay constant keeps changing every time the page refreshes.
uniqueKey = function(){
var key = firebase.database().ref().child('users').push().key;
return {
usersKey: key
};
}();
var addName = function(){
var userName = document.getElementById("name").value;
var userNamePath = firebase.database().ref('users/' + uniqueKey.usersKey + '/name');
userNamePath.set(userName);
window.location.href="age.html";
}
var addAge10 = function(){
var userAgePath = firebase.database().ref('users/' + uniqueKey.usersKey + '/age');
userAgePath.set(10);
window.location.href="blood_type.html";
}
My attempt to solve this issue was to use the revealing module pattern, but I think I'm misunderstanding something. Do I need to separate javascript files..? Please correct me if I'm using bad javascript practice.
Firebase doesn't support arrays natively, so push() is used to create a unique index that can kind-of-sort-of be used to create lists.
Every time uniqueKey is initialized, presumably every time you refresh the page, push() is called again generating another random index. Assuming the code you posted above is only ran once inside of a single javascript context, the two functions addName and addAge10 should write to the same user. My guess is that you're calling the code above multiple times at runtime, generating multiple unique keys.
// load script (unique key generated)
addName()
// load script again (different key generated)
addAge10() // set with different key
Important: Even though this could probably be done with php (I'm using WooCommerce on Wordpress), I want this script to run only on my browser. That's why I want to do it in Javascript. Hence, I'm using Custom Javascript for Websites to load my script from my browser.
What my script should do: Check if the data of a specific element has been changed.
Logic: Step 1) Get and locally remember specific string (order number) of a specific class. Step 2) Refresh the page. Step 3) Again get the specific string (order number) of a specific class. Step 4) If strings do not match, run a function (play an audio).
Problem: After page reloads, the script starts to run again from the beginning. Hence, it results in overriding the stored string. As a result, stored and newly fetched string are always equal.
Question: How do I make the script to run the 3rd step only after refresh so that the stored data doesn't override itself?
Current code:
var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
localStorage.setItem("compareOld", compareOld); // Store this element in local storage, so that it can be used after page reloads.
setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.
var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new var.
var n = compareOld.valueOf(); // Turn stored element into a number (for easy comparison later).
var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Get the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
var m = compareNew.valueOf(); // Turn fetched element into a number (for easy comparison later).
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//x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sAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
} // Function that will play the sound.
if (n!=m) {
beep();
} // Run function if two numbers are not equal.
Additional: I have gathered the parts of the code from various Questions on stackoverflow. Meaning, I have been searching about this topic for the past week. This is my first questions ever. Hopefully I formatted the question so that it easy to understand.
EDIT: The issue has been solved. I used the idea of only running the first step of function on the first load of page. This post helped me to get functionality working https://stackoverflow.com/a/22334768/7929506
The working code looks like this:
function beep() {
window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}
if (sessionStorage.getItem("visit") == null) {
var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
sessionStorage.setItem("OrderIdOld", OrderIdOld);
sessionStorage.setItem("visit", new Date());
setTimeout("window.location.reload()", 10000);
}
else {
var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
var x = sessionStorage.getItem("OrderIdOld");
if (x==OrderIdNew) {
setTimeout("window.location.reload()", 10000);
}
else {
beep();
var x = sessionStorage.getItem("OrderIdOld");
sessionStorage.removeItem("OrderIdOld");
sessionStorage.removeItem("visit");
setTimeout("window.location.reload()", 10000);
}
}
When you refresh the page first time, you can simply append a flag variable to URL to identify weather its a refresh or a first time load. Based on that, you can pass a localized variable to script and if that is set then you need to refresh else not.