Display different text everytime you call onclick function - javascript

I have this code where I am trying to pull users from my firebase database:
function pullFromDB(){
usersRef.on('value', function(snapshot) {
function next_user(){
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
}
So far it will return just one of the users as I believe it must be going through the whole users array and then putting the last name into the "users" element.
How can I iterate to the next item in the array and display a different name every time I click a button?

I have no idea what's return from DB but first try the console.log() to see what's the type of result. This will give you the answer if you are working on array or other data type.
Then if it's an array, your code:
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
It iterates the whole array and .innerHTML puts user string as the last iteration. If you want to change it each time you click a button you need a variable that will contain inteager of index that's currently aplied to id="users".
Then for each click you need to increase the variable by one.
Here is an example of working with arrays in JS. http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_element

Your are iterating through the whole array and only the last one is possible shown. You just need to assign an index and use it.
I don't know your remaining code, but by the given information, this should to the trick:
i = 0;
function pullFromDB(){
usersRef.on('value', function(snapshot) {
lastnames = Object.keys(snapshot.val().users); // get all keys, in your case the last names
function next_user(){
user = lastnames[i];
document.getElementById("users").innerHTML = user;
i++; // increase after click
// when you want to access more information of the user, you can do it like this (as an example)
// user_id = snapshot.val().users[user].id;
}

Related

How can I get a list of User with their ID (list)?

I am trying to find out how to get a user list via their id in tabular form (array).
I've tried this :
let result = message.guild.members.get(id_list)
But it doesn't work ...
id list :
var id_list = [ '223515154229231616',
'447425491041910807',
'479932358422691840',
'464536970417143828',
'299429099611357185',
'332868897646837762',
'198346639843262464',
'266078466972057600',
'334270225895653379',
'198884536363253761',
'216595784286601216',
'358993909269135371',
'248894149162565647',
'396681438688182284',
'349270173011804171',
'358319021726236672',
'216136890963853313',
'282994966014459915',
'298171616968572930',
'257809919036751872',
'239365876846034944',
'502162147942596609',
'449391921840914444',
'473229490584158208' ]
The following should do the trick
let result = id_list.map(id => client.users.get(id));
Basically, you loop through all the ids you have using .map() and fetch the user associated.
You may want to remove all the undefined results (when your bot "does not know" the user linked to a specific id), in that case you need to add the following after the previous piece of code :
result = result.filter(r => r !== undefined);
Check both the documentation of .map() and .filter() for more information
This will not work as it is for one ID at a time, not an array of them. You would need to iterate over the IDs in the array, I suggest using a for loop for this, using id_list.length as one of the parameters. For example:
for(var i = 0; i <= id_list.length; i++) {
//make the request to get the member information
}
Also, just to make sure, you might be better off using client.users.get('id'); because if the user sends a direct message, there is no guild property so an error will be thrown.
You can use
let result = id_list.map(id => client.users.get(id).tag)
That should give back an array with like
['User#0000',
'NextUser#4821'
]

How i can get a random user from my firebase user list?

I'm developing a app and need get a random user from my firebase user list. Whenever a user registers, the system updates the user count on an especific node. So, I draw a number from 1 to the total user. And now, how do I select a user based on that number?
Assuming all of your users are stored in a /users node with keys of their uid and assuming the uid's are ordered (which they always are), there are several options.
1) Load all of the users from the /users node into an array and select the one you want via it's index. Suppose we want the 4th user:
let usersRef = self.ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
let allUsersArray = snapshot.children.allObjects
let thisUserSnap = allUsersArray[3]
print(thisUserSnap)
})
While this works for a small amount of users, it could overwhelm the device if you have say, 10,000 users and lots of data stored in each node.
2) Create a separate node to just store the uid's. This is a significantly smaller dataset and would work the same way as 1)
uids
uid_0: true
uid_1: true
uid_2: true
uid_3: true
uid_4: true
uid_5: true
uid_6: true
uid_7: true
3) Reduce the size of your dataset further. Since you know how many users you have, split the dataset up into two sections and work with that.
using the same structure as 2)
let uidNode = self.ref.child("uids")
let index = 4 //the node we want
let totalNodeCount = 8 //the total amount of uid's
let mid = totalNodeCount / 2 //the middle node
if index <= mid { //if the node we want is in the first 1/2 of the list
print("search first section")
let q = uidNode.queryLimited(toFirst: UInt(index) )
q.observeSingleEvent(of: .value, with: { snapshot in
let array = snapshot.children.allObjects
print(array.last) //the object we want will be the last one loaded
})
} else {
print("search second section")
let q = uidNode.queryLimited(toLast: UInt(index) )
q.observeSingleEvent(of: .value, with: { snapshot in
let array = snapshot.children.allObjects
print(array.first) //the object we want will be the first one loaded
})
}
this method only returns 1/2 of the list so it's a much more manageable amount of data.
If you are talking about your authenticated users, the only way to retreive a list of them is by calling the corresponding admin function and applying your logic to it afterwards.
Another way could be writing a trigger for your authentication and store the userId with an incrementing number (and maybe save a totalUser field), then you only need to generate a random number and access said user.

Storing multiple data entries into a javascript object?

In my program I have to prompt the user to enter customer info.
The information includes first name, last name, phone number, and grocery items (separate each array by a comma).
The prompt keeps asking user for info until user presses cancel or enters nothing.
ex:
peter,pho,123-324-2333, beans,carots,cereal
karen,smite,122-333-1223, milk,pudding
Each time the user enters input, I need to create an object to store the info, and each object needs a property grocery item. So I assume it goes something like this.
cust = prompt("enter customer info");
while(cust != null){
var array1 = cust.split(',');
var customer = {
custinfo:array1.slice(0,3),
items:array1.slice(3,array1.length)
}
cust = prompt("enter");
}
This works for the first customer, but how do I store many entries, I don't know how much customers the user will enter. I tried creating an array of objects, if that makes any sense , like customer[], but it didn't work.I split them into arrays for later use in my homework. Also how do I make the prompt run until user enters nothing?
If you want an ordered list of items, use an Array. You can combine this with a for loop. Here is an example
function ask_questions(questions) {
var answers = [],
i,
ans;
for (i = 0; i < questions.length; ++i) { // for infinite loop, `while (true) {`
ans = prompt(questions[i] || 'enter'); // default question
if (!ans) break; // cancel or blank ends questioning
answers[i] = ans; // do what you want with the data given
}
return answers;
}
The function ask_questions takes an Array (say arr) and prompts the user arr.length times, then returns the results of the prompts as another Array
var qs = ['enter customer info', null, 'enter2']; // null will cause message "enter"
qs.length = 4; // undefined will cause message "enter"
ask_questions(qs); // ["foo", "bar", "baz", "fizz"]
However, is this really the best data structure for you? You may do better with an Object which has useful property names rather than indices and ask them for specific pieces of data such as their name and address rather than leaving it up to them. If you leave it all up to them you could end up with their pet's life story and their favourite colour etc or even nothing at all.
Finally, prompt isn't a good UX, use <input> or <textarea>s in your final revision

Javascript array push function

I have created a form in html which takes in user data. And then I use javascript to save that data into an array. Below is my code:
function test(){
var fName = document.getElementById('myName').value;
var test = ["dataOne"];
test.push("dataTwo");
test.push("dataThree");
test.push(fName);
}
THE ISSUE:
DataOne, dataTwo and dataThree are held at the following indexes in the array 0,1,2. Now the data being entered by the user through the form is being saved into a variable called "fName" and then that variable is being pushed into the array.
When I push the variable into the array its held at index 3 in the array. Every time a user inputs some data the data is saved at index 3. I wanted the next data to be saved at index 4 and the index 5 and so on. Every user submission should be at a new index. Currently if a user submits a form the array will look like this:
User 1:
[dataOne,dataTwo, dataThree,user1 input]
If a 2nd user submits a form:
User 2:
[dataOne,dataTwo, dataThree,user2 input]
The user1 input has been over written by the user 2 input.
Can anyone help.
Thanks in advance.
The problem is that you're redeclaring/overwriting the array every time the function is called. Try something like this:
var test = ["dataOne"]; //\
test.push("dataTwo"); //>which equals var test = ["dataOne", "dataTwo", "dataThree"]
test.push("dataThree"); ///
function func(){
var fName = document.getElementById('myName').value;
test.push(fName);
}
That way every new function call with push another string to the array.
Also note you I had to change the function name because not everything can be called test (the array and the function).

Get four unique items and add them to an array

I’m 100% certain this code has been working before. Now it strangely doesn’t.
The goal is to create a multiple choice quiz for a flashcard. I create an array to store the card's ids: the first one goes the current card id, then three other random ones. My goal is to make sure they don’t repeat either the first card or themselves.
This is how I do it:
// Array of cards’ ids to use
var randomCardsIds = [];
// Get the active card’s element id, add it to the array
randomCardsIds[0] = this.activeCardId;
// Get the current cards collection
var allCurrentCards = this.carouselEl.items.items;
// Get three random ids of other cards
var i = 0
while (i<3) {
// Get a random card element
var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
// Get its id
var randomCardElId = randomCardEl.body.down('.card').id;
randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);
console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));
// Make sure it is not in the array yet, and then add it
if (randomCardsIds.indexOf(randomCardElId) == -1) {
randomCardsIds.push(randomCardElId);
i++;
}
// Otherwise, the loop will have to run again
}
Basically, in a loop, for each item I check whether it already exists in the array or not. If it doesn’t, push it to the array, otherwise, run the loop again. Here is the console logging result:
Well, the first thing: it always shows the final state of the array: as if it is already filled with the results, which is weird. But the most important thing: the script does not recognise a duplicate (e.g. in the first result, 74 is repeated, and in the second to last, 47).
It only returns something different then -1, when it finds a match in the second position (returns 1, obviously). When a match is in a different position in the array, it always returns -1.
What am I doing wrong here?
Are you testing this in IE6? The problem is indexOf doesnot work with IE6.
For alternative you can check Best way to find if an item is in a JavaScript array?
A variation on a shuffling algoruthm seems to be the best bet here.

Categories

Resources