Reputation:
I am creating a store. The way it works is that when I click 'add to cart', I run a function which gets the id of the button. From that id, you can work out the name of the product, get the cost, quantity etc. For simplicity, this is the funciton code:
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
console.log(id + " " + id_quant + " " + id_name);
}
You may notice that I remove the last 4 digits from this.id
, this is because when I run the PHP to echo all the results, i make the button_id
equal to the uid
from the database, concatenated with _btn
.
What I would then like to do is to push this into an array, or use JSON.
What I am imagining is a nest array like : array[uid][cost]
, array[uid][name]
. I'm just not sure how to do this.
It should be noted that in the function, a
is actually this.id
:
<button id='1_btn' onclick='getID(this.id)'></button>
I have declared an array above the function, var array = []
.
Any help on how to push a nest would be great.
Upvotes: 2
Views: 565
Reputation: 21
instead of array
you should have an object
.
var bucket = {};
bucket[someuid] = {
"cost": 500,
"name": "Some Item"
}
Now you can access this simply by,
console.log(bucket[someuid]);
Iterating then is simple
for (item in bucket){ console.log(item['name'], item['cost']) }
Upvotes: 0
Reputation: 68373
What I would then like to do is to push this into an array, or use JSON.
You need to use an object
var obj = {};
and set values in this obj
from the function as
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
obj[ id ] = { quantity : id_quant, name : id_name }; //observe this line
console.log(id + " " + id_quant + " " + id_name);
}
Upvotes: 3