Update the value of a variable - javascript

When "Add to Cart" is clicked, the value is added to ".total-cart", and after an option is chosen in , the option value is added to the total cart value and displayed in ". total-all ". But when you click "Add to cart" again, the value of ".total-all" does not change. It is only updated when another option is selected within . Is there a way to update the value of ".total-all" automatically?
● DEMO
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> //Select with Fees
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/2/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#selectID").append(
'<option hidden="hidden" selected="selected" value="0">Choose</option><option value="' + this.gsx$price.$t.replace(/,/, '.') + '">' + this.gsx$name.$t + ' $ ' + this.gsx$price.$t + '</option>'
);
});
});
});
</script>
<script>
var shoppingCart = (function() {
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
return obj;
})();
$(document).ready(function() {
var sheetURL4 = "https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/1/public/values?alt=json";
$.getJSON(sheetURL4, function(data4) {
var entryData4 = data4.feed.entry;
console.log(data4);
jQuery.each(entryData4, function() {
$("#content").append(
this.gsx$name.$t + '<br> $ ' + this.gsx$price.$t +'<br>Add to cart<br>'
);
});
});
$.getJSON(sheetURL4, function(data4) {
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = +$(this).data('price').replace(/,/, '.');
console.log(price);
// console.log($(this).data('price'));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});
});
});
function displayCart() {
var total = shoppingCart.totalCart();
$("#selectID").change(function() {
var totalWithTax = $(this).val();
$('.total-tax').html(totalWithTax);
var sumTotalAll = total + +totalWithTax;
$('.total-all').html(sumTotalAll.toFixed(2));
});
$('.total-cart').html(total.toFixed(2));
}
displayCart();
</script>
<div id="content"></div>
<br>
<select id="selectID" style="width:200px" value="0"></select>
<p>Subtotal: $ <span class="total-cart"></span></p>
<p>Tax Value: $ <span class="total-tax"></span></p>
<p><strong>Total: $ <span class="total-all"></span></strong></p>

You can call your change event on select-box whenever any item is added to cart using $("#selectID").trigger('change') so that total value will get updated .
Demo Code:
var shoppingCart = (function() {
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for (var item in cart) {
if (cart[item].name === name) {
cart[item].count++;
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for (var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
return obj;
})();
$(document).on('click', '.add-to-cart', function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = +$(this).data('price').replace(/,/, '.');
shoppingCart.addItemToCart(name, price, 1);
$("#selectID").trigger('change') //call select
});
//use like this because select-box are dynamically created
$(document).on('change', '#selectID', function() {
var total = shoppingCart.totalCart();
var totalWithTax = $(this).val();
$('.total-tax').html(totalWithTax);
var sumTotalAll = total + +totalWithTax;
$('.total-all').html(sumTotalAll.toFixed(2));
$('.total-cart').html(total.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">item 1<br> $ 10<br>Add to cart<br>item 2<br> $ 20<br>Add to cart<br>item
3
<br> $ 30<br>Add to cart<br></div>
<br>
<select id="selectID" style="width:200px" value="0">
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="1">tax 1 $ 1</option>
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="2">tax 2 $ 2</option>
<option hidden="hidden" selected="selected" value="0">Choose</option>
<option value="3">tax 3 $ 3</option>
</select>
<p>Subtotal: $ <span class="total-cart"></span></p>
<p>Tax Value: $ <span class="total-tax"></span></p>
<p><strong>Total: $ <span class="total-all"></span></strong></p>

Try this -
$.getJSON(sheetURL4, function (data4) {
$('.add-to-cart').click(function (event) {
...
shoppingCart.addItemToCart(name, price, 1);
$('.total-all').html((shoppingCart.totalCart() + Number($("#selectID").val())).toFixed(2)); // add this, it will update total amount
displayCart();
});
});

Related

How to update order quantity (increment and decrement) in shopping cart?

I have this following code for the shopping cart with pure Javascript which can add multiply products into cart. Any clue on how to update the product quantity when the user click the + and - button in the cart without changing the order of the item in the cart?
Each button already have the product id as primary key. My idea is I could remove (using pop) the selected object using .filter() and then add (using push) back updated object into the list. But doing so will change the order of the cart.
var productList = [
{ id: 101, product: "Logitech Mouse", unitprice: 45.0 },
{ id: 102, product: "Logitech Keyboard", unitprice: 50.0 },
{ id: 103, product: "HP Mouse", unitprice: 35.0 }
];
var cart = [];
cart.length = 0;
const createCartHTMLElements = object => {
// Check type
if (typeof object !== "object") return false;
// Start our HTML
var html = "<table><tbody>";
// Loop through members of the object
debugger;
object.forEach(function(item) {
html += `<tr><td>${item.product}</td>\
<td>${item.unitprice.toFixed(2)}</td>\
<td>\
<button class="plus-btn" data-id="${item.id}">+</button>\
<label id="quantity">${item.quantity}</label>\
<button class="minus-btn" data-id="${item.id}">-</button>\
</td>\
<td>${item.total.toFixed(2)}</td>\
<td><i class="fa fa-remove del" data-id="${item.id}"></i></td>\
</tr>`;
});
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
};
const populateProducts = arrOfObjects => {
// Start our HTML
var html = "";
// Loop through members of the object
arrOfObjects.forEach(function(item) {
html += `<div class="column"><div class="card">\
<h2>${item.product}</h2>
<p class="price">RM ${item.unitprice.toFixed(2)}</p>
<p><button class=AddToCart data-id="${
item.id
}">Add to Cart</button></p>\
</div></div>`;
});
return html;
};
window.addEventListener("load", function() {
document.getElementById("productRow").innerHTML = populateProducts(
productList
);
var addToCart = document.getElementsByClassName("AddToCart");
Array.prototype.forEach.call(addToCart, function(element) {
element.addEventListener("click", function() {
debugger;
// Filter the selected "AddToCart" product from the ProductList list object.
// And push the selected single product into shopping cart list object.
productList.filter(prod => {
if (prod.id == element.dataset.id) {
prod.quantity = 1;
prod.total = prod.unitprice;
cart.push(prod);
document.getElementById(
"shoppingCart"
).innerHTML = createCartHTMLElements(cart);
return;
}
});
});
});
});
<div id="shoppingCartContainer">
<div id="shoppingCart"></div>
</div>
<hr />
<div id="productRow"></div>
You use ids multiple times; You should instead apply a class to <label id="quantity">${item.quantity}</label> so that it is <label class="quantity">${item.quantity}</label>. Also please add class price to the price and class total to the total.
Then, you can increase or lower the amount:
$(document.body).on('click', '.plus-btn', function(){
var $tr = $(this).closest('tr');
//update the quantity;
var $quantity = $tr.find('.quantity');
var n = $quantity.html();
var i = parseInt(n) + 1;
$quantity.html(i);
//update the total price
var $price = $tr.find('.price');
var price = parseFloat($price.html());
var $total = $tr.find('.total');
$total.html(i*price);
});
$(document.body).on('click', '.minus-btn', function(){
var $tr = $(this).closest('tr');
//update the quantity;
var $quantity = $tr.find('.quantity');
var n = $quantity.html();
var i = parseInt(n) - 1;
if(i<0) i = 0;
$quantity.html(i);
//update the total price
var $price = $tr.find('.price');
var price = parseFloat($price.html());
var $total = $tr.find('.total');
$total.html(i*price);
});

How to get dropdown list selected value in script using model in MVC

I'm trying to calculate the total of the selected quantity and price per piece. In some cases I have a list of allowed quantities, like 1000, 2000 etc in a dropdown list.
When I select the quantity from the dropdown it doesn't get the quantity as per the selected quantity.
View:
#if (Model.AllowedQuantities.Count > 0)
{
#Html.DropDownListFor(model => model.EnteredQuantity, Model.AllowedQuantities, new { #class = "qty-dropdown", id = "productqty" })
}
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#productqty").change(function () {
#{
var qty = Model.EnteredQuantity;
var qqt = "";
var price = "";
if (Model.AllowedQuantities.Count > 0)
{
foreach (var tierPrice in Model.TierPrices)
{
if (qty == tierPrice.Quantity)
{
price = tierPrice.Price;
}
}
} else
{
price = #Model.PriceValue.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
}
}
var prc = #price;
var qt = #qty;
var total = qt * prc;
$("#productprice").text(total);
console.log("Qty : " + qt + " Price : " + prc);
console.log("Total : " + total);
});
});
</script>

How to get the value from N dynamic inputs

I have a select with an options, this options have the number of inputs that user want to draw, after that user can type information in that inputs and finally they have to click a button to display that values, right now I'm doing this like this:
var value1 = $('#Input1').val();
The problem here is that the user can create a maximum of 200 inputs, so if I keep doing this in the above way I'll need to do that with the 200 inputs and it's a lot of code lines, my question is if exits a way to get the value of N inputs, I draw the inputs dynamically with a for loop, so all the input ID is something like Input(MyForVariable), Input1, Input2... etc, so maybe I'm thinking in create another loop to get the value of that inputs, here is my code:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
if (total == 2) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
alert(val1 + val2);
}
if (total == 3) {
var val1 = $('#Imput1').val();
var val2 = $('#Imput2').val();
var val3 = $('#Imput3').val();
alert(val1 + val2 + val3);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
Put all your inputs inside a container, and loop through them:
$('#add').on('click', function () {
$('<input />').appendTo('#myinputs');
});
$('#get').on('click', function () {
var values = [];
$('#myinputs input').each(function () {
values.push(this.value);
});
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myinputs">
<input />
</div>
<button id="add">Add another input</button>
<hr />
<button id="get">Get values</button>
You can set some attribute and get all elements that has it:
$(document).ready(function () {
$('#sel').change(function () {
draw();
});
$('#btn').click(function () {
show();
});
});
function draw() {
var selected = $('#sel').val();
var html = "";
for (i = 1; i <= selected; i++) {
html += '<input type="text" id="Imput' + i + '" to-count />';
}
$('#forms').html(html);
}
function show() {
var total = $('#sel').val();
var sum = "";
var inputs = $('[to-count]');
console.log(inputs.length);
for (let i=0; i < inputs.length ; i++){
sum += inputs[i].value;
}
alert(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="2">A</option>
<option value="3">B</option>
<option value="4">C</option>
<option value="5">D</option>
</select>
<div id="forms">
</div>
<button id="btn">Click</button>
You can get the values for each of the Select options by using the following code:
$("#sel option").each(function() {
console.log($(this).val());
});
You can always loop throw your inputs like this:
var myInputArray = [];
$('input[type="text"]').each(function(){
myInputArray.push($(this).val());
}
Then you can get your values by locking in the array:
alert(myInputArray[0]) //The first value of the array => first input

How to select quantity of individual cartItems in KnockoutJS

Hello im fairly new to knock out and im trying to have my array cartItems auto select their quantity from a drop down. Here is my code:
VIEW
<div data-bind="foreach: cartItems">
<h3 data-bind="text: fullname"></h3>
<p data-bind="text: sku"></p>
<select data-bind="quantityDropdown: number"></select>
</div>
VIEWMODEL
var number = 50;
ko.bindingHandlers.quantityDropdown = {
update: function (element) {
for (var i = 1; i < number + 1; i++) {
var selectedQty = "";
for (var x = 0; x < self.cartItems().length; x++) {
var itemqty = parseFloat(self.cartItems()[x].qty, 10);
if (i === itemqty) {
selectedQty = " selected='selected'";
}
}
// Add each option element to the select here
$(element).append("<option value='" + i + "' " + selectedQty + " class='quantity'>" + i + "</option>");
}
}
};
Now i put two items in the cart and the drop down appears. But the "selected" number is the same for both items in the cart? I know its because its not item specific. but I'm not sure how to make it item specific in Knockoutjs.
Working example:
http://jsfiddle.net/GSvnh/5085/
view :
<div data-bind="foreach: CartItems">
<h3 data-bind="text: FullName"></h3>
<p data-bind="text: Sku"></p>
<select name="qty" class="form-control" data-bind="foreach: QuantityDropdown ,value:SelectedQuantity">
<option data-bind="value: Value,text:Name"></option>
</select>
</div>
VM:
$(function () {
var MainViewModel = function () {
var self = this;
self.CartItems = ko.observableArray([]);
//For example you get below array of objects as response
var response = [{ fullname: "ABC", sku: "1234567789", qty: 12 },
{ fullname: "AAA", sku: "2323227789", qty: 20 },
{ fullname: "BBB", sku: "2311227789", qty: 33 }
];
//you map your response and for each item you create a new CartItemViewModel
self.CartItems($.map(response, function (item) {
return new CartItemViewModel(item);
}));
}
var CartItemViewModel = function (data) {
var self = this;
var number = 50;
self.FullName = ko.observable(data.fullname);
self.Sku = ko.observable(data.sku);
self.QuantityDropdown = ko.observableArray();
for (var i = 1; i < number + 1; i++) {
self.QuantityDropdown.push({ Value: i, Name: i });
}
self.SelectedQuantity = ko.observable(parseFloat(data.qty, 10));
self.SelectedQuantity.subscribe(function (newValue) {
alert("selected Qty : "+ newValue);
})
}
ko.applyBindings(new MainViewModel());
})

Calculating price from selected options in jquery

My html code :
<select class="form-control B3 pricing" name="B3">
<option data-price="0" data-cheap="0">0</option>
<option data-price="20" data-cheap="30">1</option>
<option data-price="40" data-cheap="60">2</option>
<option data-price="60" data-cheap="90">3</option>
<option data-price="80" data-cheap="120">4</option>
<option data-price="100" data-cheap="150">5</option>
</select>
My jquery code :
$(document).ready(function () {
var cheap=false;
$('.day1').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = optionSelected.val();
if(valueSelected=="Saturday")
{
cheap=true;
alert(cheap);
}else{
cheap=false;
alert(cheap);
}
});
$('.pricing').change(function(){
var price = parseFloat($('.total').data('base-price'));
$('.pricing').each(function(i, el) {
if(cheap==false){
price += parseFloat($('option:selected', el).data('price'));
}else{
price+= parseFloat($('option:selected').data('cheap'));
}
});
$('.total').val('$'+price.toFixed(2));
});
});
I want that when the day is selected as Saturday the data-cheap has to be taken and when other days are selected data-price should be calculated. Any help?
The only problem I could see is you are not passing the context to the cheap query
$(document).ready(function () {
var cheap = false;
$('.day1').on('change', function (e) {
cheap = $(this).val() == "Saturday";
});
$('.pricing').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('x', price)
$('.total').val('$' + price.toFixed(2));
});
});
});
Demo: Fiddle

Categories

Resources