This is an object I tried to create to manage a list, but somethings wrong somewhere, whenever I used the list.addItem(); for the second or third time, all the values(array) in the list.list; changes to the finally added value(array).
var list = {
list : [],
eligible: function(item){
var status = true;
var dw = (item.w*item.h*item.l)/169;
if(dw > item.m){
status = true;
}else{
status = false;
}
return status;
},
addItem : function(item){
if(this.eligible(item)){
this.list.push(item);
console.log(this.list);
this.refresh();
alertify.success('Item Added to List');
}else{
alertify.warning('Item not eligible for Freight Calculation');
}
},
removeItem : function(item){
if(this.inList(item)){
var itemIndex = this.list.indexOf(item);
if(itemIndex > -1){
this.list.splice(itemIndex,1);
alertify.success('Item Removed from List');
this.refresh();
}
}else{
alertify.error('Item NOT in List');
}
},
inList: function(item){
var bool = false;
if (this.list.filter(function(e) { return e.id === item.id; }).length > 0) {
bool = true;
}else{
bool = false;
}
return bool;
},
findItem: function (id) {
for (var i = 0; i < this.list.length; i++) {
if (this.list[i].id === id) {
return this.list[i];
}
}
},
refresh: function(){
if(this.list.length > 0){
$('.items .table tbody').empty();
var itemNo = 0;
$.each( this.list, function( key, item ) {
$('.items .table tbody').append('</tr><tr><td>' + ++itemNo + '</td><td>' + item.qty + '</td><td>' + item.m + '</td><td>' + item.h + '</td><td>' + item.w + '</td><td>' + item.l + '</td><td><button data-item=\"' + item.id + '\" class=\"btn btn-remove btn-block\"><i class=\"far fa-minus-square\"></i></button></td><td>Price</td></tr>')
});
}else{
$('.items .table tbody').html('<tr><td colspan=\"8\" style=\"text-align:center;\"> No Items Added.</td></tr>')
}
}
};
I can't find whats wrong, maybe it's because I've been trying this all day. Btw I'm new to programming.
UPDATE: This is how i call the addItem:
var id=0; //just for reference
$('.btn-add-item').click(function(){
var item = [];
item.id = ++id;
item.qty = parseInt($('input[name=qty]').val());
item.m = parseFloat($('input[name=weight]').val()).toFixed(3);
item.w = parseFloat($('input[name=width]').val()).toFixed(2);
item.h = parseFloat($('input[name=height]').val()).toFixed(2);
item.l = parseFloat($('input[name=length]').val()).toFixed(2);
item.country = $('#countrySelect').val();
list.addItem(item);
});