Javascript array push function - javascript

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).

Related

Javascript: Validating if form entries are already submitted to proceed

so I´m working with this: A form where user(workID and name) submits a claim with a date, positioID=secuence. User may have more than 1 secuence and claims are done with one or more dates. So a user may have a claim for 6/7/2017 and secuence=22. Also user may submit a claim with same date (6/7/2017) with secuence=9. User may even submit 2 diferent dates, with different secuences.
Need to validate if user has already submitted a claim for a Date, and secuence. So claims are not duplicated and an alert is triggered if it is already claimed.
To work this out: I´m doing a table/matrix where each secuence is assigned to a date already submitted. The objective is to get many date objects with each assigned secuence. So next entry is compared.
So first step:
claimList.get({workID: $rootScope.workID}, function(response) {
listByDate = [];
var validateList = response.body;
validateList.forEach(function(response){
listByDate.push({
key1: 'date',
key2: 'Secuence',
value1: response.date,
value2: response.secuence
});
}
BUilding this matrix is quite difficult
next step would be a foreach and conditional.
I will assume that data you're trying to store in is inside an object:
data = { date: x, sequence: y }
and data that you have already stored is inside an Array called dataList;
You should just check dataList for those values, if you can't find them it means you're safe and you can proceed by publishing a different and unique entry.
You should code something like the following
var occupiedSlot = dataList.find(
function(elementOfDataList) {
return elementOfDataList.date === data.date
}
);
if(occupiedSlot) alert('You've already published an entry for this date!');
If you need to publish more entries, you can repeat this script inside a function for every entry that you need to check.

Display different text everytime you call onclick function

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;
}

remember all values in an array using cookies - javascript

i want to be able to remember all values in an array using cookies, but do not know how. I am also using js-cookies.
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
As mentioned, localStorage is a better place to store this data, but using cookies follows the same steps, just need to get a set/get method for Cookies. First you need to see if there is a value. If there is you need to parse it. After you update the array, you need to convert the value to a string and store it.
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());

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

Storing information and retrieving it in javascript in a function with button

i am have made a button, and everytime i click it it takes a value from my input box, and it subtracts it and stores it back into the input box value. but what i am trying to do is, store my value into an array or anything everything my button is clicked.
so for example i want to do this,
balance = 100
button is clicked
balance is now 90
and i want
array[0] to have 100
array[1] to have 90
and everytime i want it to continue to append to the array but when i enter my button.
i have tried many things and everytime it always stores the value into array [0] and over writes it
var clicktotal=0;
var array = [];
function myfunc(){
var Bal = document.getElementById("Bank_Balance");
var Balance = Bal.value
array[clicktotal]=Balance;
console.log(clicktotal+"My array click total "+array[clicktotal]);
}
clicktotal++;
see i have this and there are some other things in the function, but the console.log is alway giving me the same number without incrimenting my variable, so it is still overwriting my array.
where my button looks like this
<input type="button" id="buy_things" value="Buy" style="width:55px; height:33px; color:#938CDD;" >
and my init function is
var Buy_button = document.getElementById("buy_things");
Buy_button.addEventListener ('click', myfunc ,true);
if there are any idea, im open to anything, i have tried using arrays, local storage, and objects but i cant seem to get it to work
You'll want to push items onto the array:
array.push(Bal.value);
Your myfunc rewritten:
function myfunc(){
var Bal = document.getElementById("Bank_Balance");
array.push(Bal.value);
console.log(array.length, "My array click total "+ Bal.value);
}
I realize my rewritten example above doesn't use clicktotal, but your example above did not use it correctly. You declared the clicktotal variable with a value of 0, and you only increment it once. Each time myfunc is called, it does not increment clicktotal, so it stays as 1, despite how many times myfunc is called.

Categories

Resources