Persisting an array to use on another html page - javascript

I need to be able to display from information in an array.
A selection is chosen by checkboxes, which is stored in the temporarySelection, then the temporarySelection info is transferred to other arrays (eg. added to restaurantSelection, then cleared for the next choices).
I need to then be able to display these arrays on a separate html page.
There's 4 different arrays to transfer to the second html page, placeSelection, hotelSelection, restaurantSelections, and sightSelections.
I've had a look around, tried a few different things, but nothing seems to be working.
Any ideas?
I've already attempted to use localstorage in a function (although I may not hav got it quite right).
Looked into cookies but I've been told not to do this as it is unnecessary as only Javascript will be using it.
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
if(!temporarySelection.includes(locationName.innerHTML)) {
console.log('pushing ' + locationName.innerHTML + ' into
temporarySelection')
temporarySelection.push(locationName.innerHTML);
} else {
var index = temporarySelection.indexOf(locationName.innerHTML);
console.log('Removing index number: ', index)
temporarySelection.splice(index, 1);
}
}
I hope that the second html page, the "results page" will show the arrays for placeSelection, hotelSelection, restaurantSelections, and sightSelections in 4 separate boxes.

Not sure how you are setting local storage. Below are the two small functions to set and get values for your array in store.
function setStore(temporarySelection){
localStorage.setItem("temporarySelection", JSON.stringify(temporarySelection));
}
function getStore(){
const temporarySelection = localStorage.getItem("temporarySelection");
if(temporarySelection)
{
return JSON.parse(temporarySelection)
}
else{
return [];
}
}
Here is your code with these functions in use
function chooseSelection(resultIndex) {
var locationName = document.getElementById('locationName-' + resultIndex);
if(!temporarySelection.includes(locationName.innerHTML)) {
console.log('pushing ' + locationName.innerHTML + ' into
temporarySelection')
temporarySelection.push(locationName.innerHTML);
} else {
var index = temporarySelection.indexOf(locationName.innerHTML);
console.log('Removing index number: ', index)
temporarySelection.splice(index, 1);
}
setStore(temporarySelection)
}
Now you can get your store values with getStore function in any page.

Related

Match players in array of game searches

I have thought about this alot but i cant find a good solution..that is also fast in Javascript.
I have an array of objects..the objects are game searches for a random player.
The array may look like this:
const GameSearches[
{fromPlayerId:"378329",goalScore:20}
{fromPlayerId:"125342",goalScore:20}
{fromPlayerId:"378329",goalScore:20}
{fromPlayerId:"918273",goalScore:20}
{fromPlayerId:"378329",goalScore:20}
]
In this array i need to rund a function called CreateNewGame(Player1,Player2).
In this array i could create games with for example index 0 and 1. Index 2 and 3. Index 4 would be left in the array as there are no more players to match on.
Anyone got a good solution to this? It would really help me out.
I have tried different filter and map without finding a good solution.
The output should call a function createnewgame
Example:
createNewGame(GameSearches[0].from,GameSearches[1].from)
this function will be called as there are two players looking for a game. they do not have they same fromPlayerId so they should match.
I see some comments on that StackOverflow is not a free codingservice..the app has thousands of lines..this is only a small part. Im asking becouse i cant figure out the logic on how to to this. I do not need a full working example.
You can try something like this
const GameSearches = [
{fromPlayerId:"378329",goalScore:20},
{fromPlayerId:"125342",goalScore:20},
{fromPlayerId:"378329",goalScore:20},
{fromPlayerId:"918273",goalScore:20},
{fromPlayerId:"378329",goalScore:20}
];
const createNewGames = (player1, player2) => console.log(player1.fromPlayerId, player2.fromPlayerId)
const getMatch = (GameSearches) => {
while([...new Set(GameSearches)].length > 1){
const player1 = GameSearches[0];
GameSearches.shift();
const player2Index = GameSearches.findIndex(el => el.fromPlayerId !== player1.fromPlayerId)
const player2 = GameSearches[player2Index];
GameSearches.splice(player2Index,1)
createNewGames(player1, player2);
}
}
getMatch(GameSearches);
I think maybe i can use the suggestion of a for loop..and it will work fine.
for (let i = 0; i < games20GoalScore.length; i = i + 2) {
if (games20GoalScore[i + 1] !== undefined) {
console.log(games20GoalScore[i] + " : " + games20GoalScore[i + 1]);
if (games20GoalScore[i].from !== games20GoalScore[i + 1].from) {
console.log("Match");
}
}
}
This code is run each time the array get a new item.

Search query parameter Javascript

I want to adding and set parameters for query string with same key and different value .
url.com/product.php?order=price.low&order=quantity.low
so there is a same key called order with different value.
i created some radio button for change product sort.
and add event listener like this :
function lowQRadio() {
document.getElementById("radio-qlow").checked=true;
params.set("order","quantity.low");
window.location.href=(location.pathname + '?' + params);
}
function highQRadio() {
document.getElementById("radio-qhigh").checked=true;
params.set("order","quantity.high");
window.location.href=(location.pathname + '?' + params);
}
function lowPRadio(){
document.getElementById("radio-plow").checked=true;
params.set("order","price.low");
window.location.href=(location.pathname + '?' + params);
}
function highPRadio(){
document.getElementById("radio-phigh").checked=true;
params.set("order","price.high");
window.location.href=(location.pathname + '?' + params);
}
some variable defined above this code and here is variables:
let url = new URL(window.location.href);
let params = new URLSearchParams(url.search);
if(params.has("order")){
var aflag=params.getAll("order");
console.log(aflag.length);
if(aflag[aflag.length-1]==="quantity.low" || aflag[aflag.length-2]==="quantity.low") {
document.getElementById("radio-qlow").checked = true;
}
else if(aflag[aflag.length-1]==="quantity.high" || aflag[aflag.length-2]==="quantity.high"){
document.getElementById("radio-qhigh").checked=true;
}
else if(aflag[aflag.length-1]==="price.low" || aflag[aflag.length-2]==="price.low"){
document.getElementById("radio-plow").checked=true;
}
else if(aflag[aflag.length-1]==="price.high" || aflag[aflag.length-2]==="price.high"){
document.getElementById("radio-phigh").checked=true;
}
so i want when user choose sort by price and quantity ,both of this radio button will checked and query changed and if user choose one of sort method ,only one parameter set and if choose another one ,both of these checked and page will be refresh
the php code or back-end worked but js code work only for one type of radio button and both sort not working!!
please help me to fix this,thanks with regards
The query string is a name-value pair collection. Names must be unique. Do you want to do something like
url.html?OrderBy=col1,col2,col3
Use a delimited string as the query string parameter value, then in your php code split the value and use logic to apply the order by.

How can I map a concatenated value for this state, without it being passed as a string?

I'm new to Javascript.
I'm building this drumpad and I want to be able to switch between different soundpacks.
The sounds are imported from a separate file and the state is written like this:
import * as Sample from '../audiofiles/soundfiles'
const drumpadData = [
{
// other stuff
soundfile: Sample.sound1a
},
If I want to load a different soundpack, I have to change the state so the last letter (a,b,c) gets changed, so instead of Sample.sound1a, it would have to be Sample.sound1b. this is the function i wrote (on App.js):
changeSamples(id) {
let choice = document.getElementById("select-samplepack").value
this.setState(prevState => {
const updatedData = prevState.data.map(item => {
let newSoundfile = "Sample.sound" + item.id + choice
item.soundfile = newSoundfile
return item
})
return {
data: updatedData
}
})
}
It works, as in the value gets changed, but instead of react interpreting that and finding the correct import, the value of soundfile just stays as a string like "Sample.soundb1", so I get a load of media resource errors.
https://aquiab.github.io/drumpad/ heres the website, you can check the console to see the error, you have to load a different soundpack to reproduce the error.
https://github.com/aquiab/drumpad and here are the files:
I've thought of some ways of cheesing it, but I want the code to stay as clean as I can make it be.
Well that's because it is in fact a string. When you do:
"Sample.Sound" + item.id + choice you are doing type coersion. In JavaScript, that means you are converting the value of all data-types so that they share a common one. In this case your output resolves into a string. This will not be effective in finding the right sound in your dictionary.
Instead, what you need is bracket notation: Object[property]
Within the brackets we can define logic to identify the designated key belonging to the Object.
For example: Sample["sound" + item.id + choice] would evaluate to Sample["sound1b"] which is the same as Sample.sound1b
changeSamples(id) {
let choice = document.getElementById("select-samplepack").value
this.setState(prevState => {
const updatedData = prevState.data.map(item => {
item.soundfile = Sample["sound" + item.id + choice]
return item
})
return {
data: updatedData
}
})
}
I can think of two approaches here.
import Sample in App.jsx. and update sound file.
import * as Sample from '../audiofiles/soundfiles'
changeSamples(id) {
let choice = document.getElementById("select-samplepack").value
this.setState(prevState => {
const updatedData = prevState.data.map(item => {
let newSoundfile = Sample[`sound${item.id}${choice}`]
item.soundfile = newSoundfile
return item
})
return {
data: updatedData
}
})
}
You should save mapping of files in other object and update mapping and use mapping in drumpadData soundfile key.
Your problem comes from this line :
let newSoundfile = "Sample.sound" + item.id + choice
Here you are concatening your values item.id and choice with a string, so the result is a string and Sample is not interpreted as your imported object.
What you need is to wright something like
const sampleItem = "sound" + item.id + choice
let newSoundfile = Sample[sampleItem]
When you access an object property with the notation myObject[something], what's inside the bracket get interpreted. So in my example sample (which is a string because I concatenated a string "sound" with the variables) will be replaced with its string value (ex: "sound1a"), and newSoundFile will have as value the result of Sample["sound1a"].
I hope it make sens.

I'm trying to use jquery to create a div containing columns but I can't get my array to format correctly

I have an array that contains dates. and for some reason I can't get it to show on my screen I've been debugging for a few days now and I've tracked it down to a single line, but the line has worked before and I can't figure out what the issue might be.
The array looks like this:
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"...];
It's passed as an argument from another function, but that's how it's showing in console.log().
I might be going about this the wrong way, maybe even a lot further around then I need to but this is what I've come up with:
1. function setTHead(selectItems) {
2 var formatString;
3. for (var x = 0; x < 12; x++) {
4. formatString = selectItems[x].replace(/[^0-9/-]/g, "").toString();
5. console.log(selectItems);
6. $('#datTab').append("<div id='col" + x + "' class='column'>'" + formatString + "'</div>");
7. }
8. }
the array up top is what's showing from the console.log 5 lines down.
the sixth line is what is seeming to give me issues. Nothing is put on the page at all.
I'm getting a console error saying:
jQuery.Deferred exception: selectItems is undefined setTHead#http://localhost/mySite/script.js:136:9
startUp2#http://localhost/mySite/script.js:146:5
#http://localhost/mySite/table.php:19:9
mightThrow#http://localhost/mySite/lib/jquery.js:3586:52
resolve/</process<#http://localhost/mySite/lib/jquery.js:3654:49
setTimeout handler*resolve/<#http://localhost/mySite/lib/jquery.js:3692:37
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
fire#http://localhost/mySite/lib/jquery.js:3458:21
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
ready#http://localhost/mySite/lib/jquery.js:3923:13
completed#http://localhost/mySite/lib/jquery.js:3933:9
EventListener.handleEvent*#http://localhost/mySite/lib/jquery.js:3949:9
#http://localhost/mySite/lib/jquery.js:39:9
#http://localhost/mySite/lib/jquery.js:17:3
undefined
followed by:
TypeError: selectItems is undefined
and thats pointing to line 6.
if anyone has any advice I would be very much appreciative. Thank you in advance.
EDIT: A little more code:
function startTblView(defSel) {
if (defSel === true) {
setCookie('defSel', true, 7);
} else{
setCookie('defSel', false, 7);
}
saveSelected();
window.open('table.php', '_self');
defSel = getCookie('defSel');
if (defSel) {
selectItems = getDefDates();
}else {
selectItems = reGetSelected();
}
setTHead(selectItems);
}
defSel, is a boolean passed from my last page stating whether I'm doing a default view or a custom view, the custom view is passed from saveSelected();
saveSelected is a function for just saving the selected global value as a cookie so I can pull it out on the next page.
getDefDates pulls the default values for the array
reGetSelected, gets the selected array from the cookie.
I apologize for wonky naming conventions. I'm the only one working on this site and I'm just making sure the names don't overlap.
You can do this :
HTML code
<div id="datTab"></div>
JS code
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"];
function setTHead(selectItems) {
var formatString;
$.each( selectItems, function( index, value ){
formatString = value.replace(/[^0-9/-]/g, "").toString();
$('#datTab').append("<div id='col" + index + "' class='column'>'" + value + "'</div>");
});
};
You can use $.each, its better than 'for' with javascript.
The .each() method is designed to make DOM looping constructs concise
and less error-prone. When called it iterates over the DOM elements
that are part of the jQuery object. Each time the callback runs, it is
passed the current loop iteration, beginning from 0. More importantly,
the callback is fired in the context of the current DOM element, so
the keyword this refers to the element.
I did a JsFiddle
Here.

Implementing Infinite Scrolling with Firebase?

var self = this;
var firebaseRef = new Firebase(baseUrl + '/sparks');
firebaseRef.limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
self.addChild(childSnapshot); // adds post to a <div>
});
My code currently loads the last 5 posts and will load any new posts. However, I'd also like to be able to load older posts as well. I have a button that when clicked will call a function (that I'm unsure of how to implement) that loads older posts. How do I retrieve these older posts?
(The arrow just signifies that I want to retrieve posts starting from the bottom and working my way up to the top)
You need to think a bit backwards to do this. When you get the results for your query for the first page, remember the first item in the results:
firebaseRef.endAt().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
self.addChild(childSnapshot); // adds post to a <div>
});
While you cannot access child items by index with Firebase, you can store the key of an item and use that to start a next query.
var firstKnownKey;
firebaseRef.orderByKey().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
if (!firstKnownKey) {
firstKnownKey = childSnapshot.key;
}
self.addChild(childSnapshot); // adds post to a <div>
});
Now you have a variable firstKnownKey that has the first key you've ever seen. To get the previous batch of children, you pass that value in to endAt() when you fire your next query:
firebaseRef.orderByKey().endAt(firstKnownKey).limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
if (!firstKnownKey) {
firstKnownKey = childSnapshot.key;
}
self.addChild(childSnapshot); // adds post to a <div>
});
Answers to similar questions of the past few days:
Can I get the nth item of a firebase "query"?
Firebase results range using startAt and endAt
Since endAt() is inclusive, the last item gets repeated every time I do the infinite scroll, so I did a little modification to frank van puffen 's answer.
I initiate a list childrenVal to store all the values, another list childrenKey to store all the keys and a var firstKnownKey, as frank van puffen sugests.
var childrenVal=[];
var childrenKey=[];
var firstKnownKey = "";
For the first time you make the query, you get the last 5 elements:
getFirst(){
firebaseRef.orderByKey().limitToLast(5).once('value')
.then((snap)=>{
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length-1];
});
}
In your next query, you won't want your firstKnownKey to get repeated, so I did the following function:
exclude(key){
return key.substring(0, key.length - 1) + String.fromCharCode(key.charCodeAt(key.length - 1) - 1)
}
and for the query itself, the following function:
getNext() {
firebaseRef.orderByKey().endAt(exclude(firstKnownKey)).limitToLast(5).once('value')
.then((snap) => {
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length - 1];
});
}

Categories

Resources