This is the structure of my Array:
[{"stockCode":"PALLET CARDS","quantity":"2"},
{"stockCode":"PALLET CARDS","quantity":"3"},
{"stockCode":"CBL202659/A","quantity":"1"},
{"stockCode":"CBL201764","quantity":"3"}]
When the order button
is clicked I would like to check if a stockCode
exists in this array
. However each time I do this I get -1 returned.
This is the code where I check for the stockCode
:
$(".orderBtn").click(function(event){
//Check to ensure quantity > 0
if(quantity == 0){
console.log("Quantity must be greater than 0")
}else{//It is so continue
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
//Order Item (contains stockCode and Quantity) - Can add whatever data I like here
var orderItem = {
'stockCode' : stockCode,
'quantity' : quantity
};
//Check if cookie exists
if($.cookie('order_cookie') === undefined){
console.log("Creating new cookie");
//Add object to the Array
productArray.push(orderItem);
}else{//Already exists
console.log("Updating the cookie")
productArray = JSON.parse($.cookie('order_cookie'));
//Check if the item already exists in the Cookie and update qty
if(productArray.indexOf(stockCode)!= -1){
//Get the original item and update
console.log("UPDATING EXISTING ENTRY " + productArray.indexOf("PALLET CARDS"));
}
else{
console.log("ADDING NEW ENTRY ");
//Insert the item into the Array
//productArray.push(orderItem);
}
}
}
//Update the Cookie
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
//Testing output of Cookie
console.log($.cookie('order_cookie'));
});
I get a reference to the stockCode when the user clicks on the order button
:
var stockCode = $(this).closest('li').find('.stock_code').html();
I would like to check if this stockCode is already in the array
and if it is then I will not be adding a new entry, but rather, updating an existing one.