How to parse JSON and put in HTML with infinite scroll? - javascript

I want to read data from a json file and put in html. The json contains lots of data, so I want to use infinite scroll with it.
I have searched and found this example: https://codepen.io/anantanandgupta/pen/oLLgyN
var dataJSON = '[{"FeeType":"Domestic POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"Domestic PIN Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"International PIN Declined Fee ","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"ATM Domestic Fee <sup>1</sup>","FeeDescription":"One (1) no cost ATM withdrawal per deposit1, then $1.75 per transaction thereafter","FeeAmount":"1.75"},{"FeeType":"Domestic ATM Balance Inquiry Fee <sup>1</sup>","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.50"},{"FeeType":"Domestic ATM Declined Fee <sup>1</sup>","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International ATM Withdrawal Fee <sup>1</sup>","FeeDescription":"per transaction","FeeAmount":"3.00"},{"FeeType":"International ATM Balance Fee ","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.95"},{"FeeType":"International ATM Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"International OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"Currency Conversion Fee","FeeDescription":"3% of transaction amount","FeeAmount":"3.00%"},{"FeeType":"Card Replacement Fee","FeeDescription":"One (1) no cost replacement per calendar year or upon expiration; $5.00 per request thereafter for lost, stolen, and damaged cards.","FeeAmount":"5.00"},{"FeeType":" Expedited Card Replacement Fee ","FeeDescription":"$20.00 (per Card; an additional fee when a Card is reissued or replaced for any reason with requested expedited delivery)","FeeAmount":"20.00"},{"FeeType":"Check Refund Fee","FeeDescription":"$12.50 per refund check (When a refund check is issued for the remaining Card balance.","FeeAmount":"12.5"}]';
var dataObject = JSON.parse(dataJSON);
var listItemString = $('#listItem').html();
dataObject.forEach(buildNewList);
function buildNewList(item, index) {
var listItem = $('<li>' + listItemString + '</li>');
var listItemTitle = $('.title', listItem);
listItemTitle.html(item.FeeType);
var listItemAmount = $('.amount', listItem);
listItemAmount.html(item.FeeAmount);
var listItemDesc = $('.description', listItem);
listItemDesc.html(item.FeeDescription);
$('#dataList').append(listItem);
}
This is what I want for parse the json. But it does not include infinite scroll. So how to make it infinite scroll?

You should add an event listener to the div in which you want to append the content (in your case $('#dataList') ), so that every time there is a scroll in the scrolled div the script checks if the bottom was reached.
// Detect when scrolled bottom
$('#dataList').addEventListener('scroll', function() {
if ($('#dataList').scrollTop + $('#dataList').clientHeight >= $('#dataList').scrollHeight) {
loadMore();
}
});
//Loading more elements
function loadMore(){
var dataJSON = '[{"FeeType":"Domestic POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"Domestic PIN Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"International PIN Declined Fee ","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"ATM Domestic Fee <sup>1</sup>","FeeDescription":"One (1) no cost ATM withdrawal per deposit1, then $1.75 per transaction thereafter","FeeAmount":"1.75"},{"FeeType":"Domestic ATM Balance Inquiry Fee <sup>1</sup>","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.50"},{"FeeType":"Domestic ATM Declined Fee <sup>1</sup>","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International ATM Withdrawal Fee <sup>1</sup>","FeeDescription":"per transaction","FeeAmount":"3.00"},{"FeeType":"International ATM Balance Fee ","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.95"},{"FeeType":"International ATM Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"International OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"Currency Conversion Fee","FeeDescription":"3% of transaction amount","FeeAmount":"3.00%"},{"FeeType":"Card Replacement Fee","FeeDescription":"One (1) no cost replacement per calendar year or upon expiration; $5.00 per request thereafter for lost, stolen, and damaged cards.","FeeAmount":"5.00"},{"FeeType":" Expedited Card Replacement Fee ","FeeDescription":"$20.00 (per Card; an additional fee when a Card is reissued or replaced for any reason with requested expedited delivery)","FeeAmount":"20.00"},{"FeeType":"Check Refund Fee","FeeDescription":"$12.50 per refund check (When a refund check is issued for the remaining Card balance.","FeeAmount":"12.5"}]';
var dataObject = JSON.parse(dataJSON);
var listItemString = $('#listItem').html();
dataObject.forEach(buildNewList);
}
//Building an element
function buildNewList(item, index) {
var listItem = $('<li>' + listItemString + '</li>');
var listItemTitle = $('.title', listItem);
listItemTitle.html(item.FeeType);
var listItemAmount = $('.amount', listItem);
listItemAmount.html(item.FeeAmount);
var listItemDesc = $('.description', listItem);
listItemDesc.html(item.FeeDescription);
$('#dataList').append(listItem);
}

Related

How to subtract quantity from the equipment table when there's a new borrow transaction made?

I'm a Laravel newbie and I recently started working on a equipment management system whereby the admin adds quantity stock one each equipment to the system and when admin let the user borrow the equipment it deducts the quantity that the user wants from the equipment stock table. My only challenge is how to make the system to subtract quantity that the borrower wants from the equipment stock table?
Here's my controller for the button "borrow"
So when I click the borrow button it will deducts the ('quantity_item') to the equipment stock table ('e_quantity')
public function borrow($id){
$first = Reservation::where('id', $id)->first();
$kl = $first->name;
$mn = $first->Name_item;
$st = $first->quantity_item; //this is the quantity that the borrower wants
$op = $first->dt_item;
$qr = $first->room_item;
$first->delete();
$second = new BorrowedItems();
$second->bname = $kl;
$second->bdate = $mn;
$second->itemb = $op;
$second->bquantity = $st;
$second->broom = $qr;
$second->save();
return redirect()->back()->with('message','Item Borrowed Successfully!');
}
This is my Equipment Stock Table
This is my BorrowedItem Table
so when I click the borrow button the data from reservationtable will transfer here
This is my Reservation Table

Subject of Email Should changed based on Cell Value

I have created a Google script to send an email once the user submits the form. The script is running very well. But one thing that is not proper is the subject of the email. I want the email subject to be changed based on the cell value.
Currently, I am using this script:
function afterFormSubmit(e) {
const info = e.namedValues;
const pdfFile = createPDF(info);
const entryRow = e.range.getRow();
const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Final Responses");
ws.getRange(entryRow, 64).setValue(pdfFile.getUrl());
ws.getRange(entryRow, 65).setValue(pdfFile.getName());
sendEmail(e.namedValues ['Email address'][0],pdfFile);
}
function sendEmail(email,pdfFile){
var DOR = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Final Responses").getActiveCell();
var NOO = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Final Responses").getActiveCell();
var subject = "DTR - KCCO - " + NOO + " - " + DOR;
var body = "Sir," + String.fromCharCode(10)+ String.fromCharCode(10) + "Please find the attached Daily Transaction Report for the outlet " + NOO + " for " + DOR + "." + String.fromCharCode(10) + String.fromCharCode(10)+ "--" + String.fromCharCode(10) + "Thanks & Regards" + String.fromCharCode(10) + "KCCO - Automation Team" ;
GmailApp.sendEmail(email, subject, body, {
attachments: [pdfFile],
name: 'KCCO - Automation Team'
});
}
function createPDF(info) {
const pdfFolder = DriveApp.getFolderById("1ME3EqHOZzBZDBLNPHQxLjf5tWiQpmE8u");
const tempFolder = DriveApp.getFolderById("1ebglel6vwMGXByeG4wHBBvJu9u0zJeMJ");
const templateDoc = DriveApp.getFileById("1kyFimRMdHQZV85F5P6JyCHv1DQ3KJFv1hx5o7lIcNZo");
const newTempFile = templateDoc.makeCopy(tempFolder);
const openDoc = DocumentApp.openById(newTempFile.getId());
const body = openDoc.getBody();
body.replaceText("{Name of Person}", info['Name of Person'][0]);
body.replaceText("{Date of Report}", info['Date of Report'][0]);
body.replaceText("{Name of Outlet}", info['Name of Outlet'][0]);
body.replaceText("{Opening Petty Cash Balance}", info['Opening Petty Cash Balance'][0]);
body.replaceText("{Total Petty Cash Received}", info['Total Petty Cash Received'][0]);
body.replaceText("{Closing Petty Cash Balance}", info['Closing Petty Cash Balance'][0]);
body.replaceText("{Total Petty Cash Paid}", info['Total Petty Cash Paid'][0]);
body.replaceText("{Available Float Cash Balance}", info['Available Float Cash Balance'][0]);
body.replaceText("{Milk for Outlet}", info['Milk for Outlet'][0]);
body.replaceText("{Cold Drink And Ice Cube Purchased}", info['Cold Drink And Ice Cube Purchased'][0]);
body.replaceText("{Goods Purchased for Outlet}", info['Goods Purchased for Outlet'][0]);
body.replaceText("{Staff Milk/Toast etc.}", info['Staff Milk/Toast etc.'][0]);
body.replaceText("{Water Tank Charges}", info['Water Tank Charges'][0]);
body.replaceText("{Repair And Maintenance}", info['Repair And Maintenance'][0]);
body.replaceText("{Petrol Expenses}", info['Petrol Expenses'][0]);
body.replaceText("{Freight Paid}", info['Freight Paid'][0]);
body.replaceText("{Purchase of Soya Chaap}", info['Purchase of Soya Chaap'][0]);
body.replaceText("{Purchase of Rumali Roti}", info['Purchase of Rumali Roti'][0]);
body.replaceText("{Purchase of Egg Tray}", info['Purchase of Egg Tray'][0]);
body.replaceText("{Other Expenses}", info['Other Expenses'][0]);
body.replaceText("{Please Specify Other Expenses}", info['Please Specify Other Expenses'][0]);
body.replaceText("{Total Tip Amount PAYTM & CARD}", info['Total Tip Amount PAYTM & CARD'][0]);
body.replaceText("{Cash Sales - Outlet}", info['Cash Sales - Outlet'][0]);
body.replaceText("{Cash Sales - KCCO App}", info['Cash Sales - KCCO App'][0]);
body.replaceText("{Card Sales}", info['Card Sales'][0]);
body.replaceText("{Credit/Udhar Sales}", info['Credit/Udhar Sales'][0]);
body.replaceText("{Paytm Sales}", info['Paytm Sales'][0]);
body.replaceText("{KCCO App Sales Razor Pay}", info['KCCO App Sales Razor Pay'][0]);
body.replaceText("{Swiggy Sales}", info['Swiggy Sales'][0]);
body.replaceText("{Zomato Sales}", info['Zomato Sales'][0]);
body.replaceText("{Dunzo Sales}", info['Dunzo Sales'][0]);
body.replaceText("{Zomato Gold Sales}", info['Zomato Gold Sales'][0]);
body.replaceText("{Dine Out Sales}", info['Dine Out Sales'][0]);
body.replaceText("{Total Cancelled Bill Amount}", info['Total Cancelled Bill Amount'][0]);
body.replaceText("{Total Sales of the Day - Total of Above}", info['Total Sales of the Day - Total of Above'][0]);
body.replaceText("{Total Sales of the Day - As Per PetPooja}", info['Total Sales of the Day - As Per PetPooja'][0]);
body.replaceText("{Old Due Receipts - Cash}", info['Old Due Receipts - Cash'][0]);
body.replaceText("{Old Due Receipts - Other Modes}", info['Old Due Receipts - Other Modes'][0]);
body.replaceText("{Tip Receipts - Card}", info['Tip Receipts - Card'][0]);
body.replaceText("{Tip Receipts - Paytm}", info['Tip Receipts - Paytm'][0]);
body.replaceText("{Currency Note of INR 2000}", info['Currency Note of INR 2000'][0]);
body.replaceText("{Currency Note of INR 500}", info['Currency Note of INR 500'][0]);
body.replaceText("{Currency Note of INR 200}", info['Currency Note of INR 200'][0]);
body.replaceText("{Currency Note of INR 100}", info['Currency Note of INR 100'][0]);
body.replaceText("{Currency Note of INR 50}", info['Currency Note of INR 50'][0]);
body.replaceText("{Currency Note of INR 20}", info['Currency Note of INR 20'][0]);
body.replaceText("{Currency Note of INR 10}", info['Currency Note of INR 10'][0]);
body.replaceText("{Other Currency Note/Coins}", info['Other Currency Note/Coins'][0]);
body.replaceText("{Total Available Cash to Handover}", info['Total Available Cash to Handover'][0]);
body.replaceText("{Total No. of Credit Bills}", info['Total No. of Credit Bills'][0]);
body.replaceText("{S.No.//Name of Person// Mobile No// Credit Approval By// Bill No// Total Amount of Credit}", info['S.No.//Name of Person// Mobile No// Credit Approval By// Bill No// Total Amount of Credit'][0]);
body.replaceText("{Total No. of Bills of Credit Recovery}", info['Total No. of Bills of Credit Recovery'][0]);
body.replaceText("{S.No.//Name of Person// Mobile No// Mode of Payment// Bill No// Total Amount Received}", info['S.No.//Name of Person// Mobile No// Mode of Payment// Bill No// Total Amount Received'][0]);
body.replaceText("{Total No. of Complementary Bills During the Day}", info['Total No. of Complementary Bills During the Day'][0]);
body.replaceText("{S.No.//Name of Person// Mobile No//Reason// Bill No//Amount Settled}", info['S.No.//Name of Person// Mobile No//Reason// Bill No//Amount Settled'][0]);
body.replaceText("{Total No. of Cancelled Bills During the Day}", info['Total No. of Cancelled Bills During the Day'][0]);
body.replaceText("{S.No.//Name of Person// Mobile No// Bill No// Bill Amount}", info['S.No.//Name of Person// Mobile No// Bill No// Bill Amount'][0]);
body.replaceText("{S.No.// Bill No// Mode of Payment//Tip Amount Received}", info['S.No.// Bill No// Mode of Payment//Tip Amount Received'][0]);
body.replaceText("{No. of Cylinders Received at Outlet}", info['No. of Cylinders Received at Outlet'][0]);
body.replaceText("{Timestamp}", info['Timestamp'][0]);
body.replaceText("{Email address}", info['Email address'][0]);
//body.replaceText("{Total of Cash Denomination}", info['Total of Cash Denomination'][0]);
openDoc.saveAndClose();
const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName('DTR - KCCO - '+info['Name of Outlet'][0]+ " - " + info['Date of Report'][0]);
tempFolder.removeFile(newTempFile);
return pdfFile;
}
The link of the Response submitted by a Google form is as below:
https://docs.google.com/spreadsheets/d/1m6Aca0TcLf5UZ7P9CvAdQDokoazQljsqDT6CGh0K3j4/edit?usp=sharing
I want the Name of the Outlet i.e. F2:F
and Date of Report i.e. C2:C
E.g. if the user submits the form now data will appear in the 37th row so the name of the outlet and report should be F37 and C37.
Please guide.

I cannot parse multi-row json array and put it into the html elements

var dataJSON = '[{"FeeType":"Domestic POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"Domestic PIN Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"International PIN Declined Fee ","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"ATM Domestic Fee <sup>1</sup>","FeeDescription":"One (1) no cost ATM withdrawal per deposit1, then $1.75 per transaction thereafter","FeeAmount":"1.75"},{"FeeType":"Domestic ATM Balance Inquiry Fee <sup>1</sup>","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.50"},{"FeeType":"Domestic ATM Declined Fee <sup>1</sup>","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International ATM Withdrawal Fee <sup>1</sup>","FeeDescription":"per transaction","FeeAmount":"3.00"},{"FeeType":"International ATM Balance Fee ","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.95"},{"FeeType":"International ATM Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"International OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"Currency Conversion Fee","FeeDescription":"3% of transaction amount","FeeAmount":"3.00%"},{"FeeType":"Card Replacement Fee","FeeDescription":"One (1) no cost replacement per calendar year or upon expiration; $5.00 per request thereafter for lost, stolen, and damaged cards.","FeeAmount":"5.00"},{"FeeType":" Expedited Card Replacement Fee ","FeeDescription":"$20.00 (per Card; an additional fee when a Card is reissued or replaced for any reason with requested expedited delivery)","FeeAmount":"20.00"},{"FeeType":"Check Refund Fee","FeeDescription":"$12.50 per refund check (When a refund check is issued for the remaining Card balance.","FeeAmount":"12.5"}]';
var dataObject = JSON.parse(dataJSON);
var listItemString = $('#listItem').html();
dataObject.forEach(buildNewList);
function buildNewList(item, index) {
var listItem = $('<li class="collection-item">' + listItemString + '</li>');
var listItemTitle = $('.title', listItem);
listItemTitle.html(item.FeeType);
var listItemDesc = $('.description', listItem);
listItemDesc.html(item.FeeDescription);
$('#myUL').append(listItem);
}
var myObj2 = {
"kelimeler": [
{
"title": "",
"description": "T�rkiyenin en b�y�k do_rudan sat�_ _irketi"
},
{
"title": "Aktif Temsilci",
"description": "Bir kampanyada sipari_ veren ve �d�l sat�_ tutar� s�f�rdan b�y�k olan temsilci"
},
] }
I found some code on the internet.
var dataObject = JSON.parse(dataJSON);
this works perfectly but it is really hard for me to manage a single line json array. I just want to use myObj2 and access the title and desciption.
How can I access the elements inside myObj2 > 'keliemeler' . I tried item.kelimeler.title something but it didn't work.
Thanks.
item.kelimeler will never shown since it's only in myObj2, and item is taken from dataJSON that doesn't have kelimeler.

Selected List Dynamic Calculations in Cart Difficulty

I'm working on a program where I add items to a cart and I have the totals compute dynamically as things are added and removed. My problem is when I change the totals with a selected list. Right now only the first item in the shopping cart's quantity selector works.
Also when I add new items to the cart the quantity switches back to 1. Anyway to solidify my quantity values?
I would REALLY appreciate any help that can be given. I've been looking at this code for hours trying to figure out why I can't get everything to work right.
Here's my code revolving around the cart and manipulating it:
//Activates "Add" button so cart can be populated
$('#item-list').on('click', '.addme', function(){
// 1. Read the item index using data- attribute
var index = $(this).data('index');
if(!inCart(index)){
cart.push(index);
}
// 3. Update the cart list and total credits
displayCartItems();
checkCart();
// update price
calculateTotalPrice();
});
//function to check if items are in cart
function inCart(index){
for (var i=0; i<cart.length; i++){
if (cart[i] == index)
return true;
}
return false;
}
//Displays the shopping cart items
function displayCartItems(){
// create a table row for each item in cart array
var itemInfo = '';
for (var i=0; i<cart.length; i++){
var index = cart[i];
itemInfo += createTableRow(index);
}
$('#selected-list').html(itemInfo);
}
//Constructs the shopping cart table
function createTableRow(index){
var trow = '';
trow += "<tr><td>"+item_list[index].title + "</td>>";
trow += "<td id='itemsprice'>"+item_list[index].price + "</td>";
trow += "<td><select class='item-quantity' data-quantity='"+index+"'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option></td>";
trow += "<td id='tc-item'>"+item_list[index].price+"</td>"
trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
return trow;
}
//When quantity is changed change the value and compute new totals
$('#selected-list').on('change', '.item-quantity', function(){
calculateTotalPrice();
});
//If delete button is pressed in cart, the item is removed from the cart
$('#selected-list').on('click', '.delete-item', function(){
var index = $(this).val();
removeItemFromCart(index);
calculateTotalPrice();
checkCart();
});
function checkCart(){
if(cart.length == 0){
$('#empty-cart').html("Your cart is empty!");
} else {
$('#empty-cart').html("");
}
}
//function to remove items from the shopping cart
function removeItemFromCart(index){
// identify and remove the index from the cart and redisplay cart table
var pos = -1;
for (var i=0; i<cart.length; i++){
if (index == cart[i]){
pos = i;
break;
}
}
if (pos>-1){
cart.splice(pos, 1);
// reset the cart table
displayCartItems();
} else {
alert("Could not find!");
}
}
function calculateTotalPrice(){
var quantity = $('.item-quantity').val();
var subtotal = 0;
var tax = 0;
var shipping = 0;
var total = 0;
//for loop to calculate the subtotal
for(var i = 0; i < cart.length; i++){
var productPrice = item_list[cart[i]].price;
subtotal += productPrice * quantity;
}
//Percent taxed is 6%
var taxPerc = .06;
//Calculating taxes
tax = subtotal * taxPerc;
//Percent for shipping is 2%
var shippingPerc = .02;
//Calculating shipping
shipping = subtotal * shippingPerc;
//Calculating total
total = subtotal + tax + shipping;
//Displaying totals
//$('#tc-item').html(totalItemPrice.toFixed(2));
$('#subtotal').html(subtotal.toFixed(2));
$('#tax').html(tax.toFixed(2));
$('#shipping').html(shipping.toFixed(2));
$('#total').html(total.toFixed(2));
}
//Activates the Display cart and Hide cart buttons in shopping cart
$('#show-cart').on('click', function(){
$('#selected-list').show();
});
$('#hide-cart').on('click', function(){
$('#selected-list').hide();
});
I'm positive my calculateTotalPrice() function needs some tweaking, but I've been unable to figure out how to fix it thus far.
Here's the rest of my code if anyone needs it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sam's Discount Store </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<style type="text/css">
.courselist { cursor: pointer;}
.t-head { color: #fff; background-color: #333366; font-size: 20px; line- height: 20px; }
#top-box, #footer { background-color: #330066; color: #fff; text-align: center;}
#content {border: 1px solid #330099;}
</style>
<script>
$(function(){
/* The following function defines a constructor for creating an array of objects with four properties.
The keyword "this" refers to the instance of the object
*/
function Item(type,title,description,price){
this.type = type;
this.title = title;
this.description = description;
this.price = price;
}
//create an array to store items
var item_list = [];
var cart = []; //store index of elements in the shopping cart
//add items
//add baseballgear items
item_list.push(new Item('baseballgear','Louisville Slugger', 'The finest craftsmanship and finest materials ensure stepping to the plate with the Louisville Slugger® M9 Maple M110 Bat will allow you to swing what the pros swing.', 79.99 ));
item_list.push(new Item('baseballgear','Marucci Bat', 'Named for one of the most lethal hitters in the game, the Marucci® CUTCH22 Pro Model Baseball Bat features the same cut and finish swung by MLB® center fielder, Andrew McCutchen. The "Cutch" features a large, powerful, balanced barrel with a sleek cherry red and grey finish to deliver maximum performance at the plate. This adult wooden bat is also handcrafted and bone-rubbed to ensure superior quality and surface hardness.', 139.99));
item_list.push(new Item('baseballgear', 'Rawlings Glove', "Unrivaled quality season after season, the Rawlings® 11.25'' Pro Preferred® Series Glove returns to provide elite craftsmanship and superior performance for elite middle infielders.",349.99));
item_list.push(new Item('baseballgear', 'Wilson Glove', "Enhance your field performance with unrivaled dependability with the Wilson® 11.5 A2000™ Series Glove. Made with Pro Stock® leather for long-lasting performance, this glove's construction is preferred by professionals for its top-notch quality. Dri-Lex® technology in the wrist lining transfers moisture away from the skin to keep you cool and dry. The advanced design has been improved upon by the Wilson&Reg; Advisory Staff.",249.99 ));
item_list.push(new Item('baseballgear', 'Easton Baseball Helmet', 'Give your favorite player maximum protection at the plate with the Easton® Junior Z5 Elite Baseball Helmet. The ABS shell withstands impact and disperses energy away from the head, with a stylish Digi-Camo design. Featuring dual density foam liner for advanced comfort, this helmet boasts BioDri™ padded inner liner to wick moisture away from the skin to keep them cool and dry. Wrapped ear pads provide enhanced coverage around the head.', 54.99));
item_list.push(new Item('baseballgear', 'Rawlings Batting Gloves', 'Get the most out of your batting gloves this season with the Rawlings® Adult Workhorse 950 Batting Gloves. These gloves feature an Oiltac® leather palm pad to provide better grip and softness. Equipped with a Dura-Plus™ pad for added protection in the palm, the Dynamic Fit System™ provides greater comfort, flex, and feel during every play. The adjustable wrist closure is reinforced to provide a more secure fit', 34.99));
//add soccergear items
item_list.push(new Item('soccergear', 'Nike Ordem Soccer Ball', 'Hit the back of the net with the The Nike® Ordem 3 PL Soccer Ball. The Ordem 3 is the official match ball of the English Premier League for the 2015-2016 season. This FIFA® approved ball features Aerowtrac grooves and a micro-textured casing for accurate flight. The carbon latex bladder and fuse-welded construction allow for an exceptional touch while the vivid visual Power Graphics allow you to track the ball so you can react quickly.', 150.00));
item_list.push(new Item('soccergear', 'Wilson Shinguard', 'Maximize your protection for practice or game day with the Wilson® NCAA® Forte ll Soccer Shinguard. This high impact shinguard is constructed of a removable inner shell for adjustable protection to diffuse impact during elite-level play. Its Lycra® sleeve contains power band enhancements for added compression and blood circulation. Focus on your game with the Wilson® NCAA® Forte ll Soccer Shinguard.', 24.99 ));
item_list.push(new Item('soccergear', 'Adidas Goalie Gloves', 'Protect the goal line with intensity when you sport the adidas® Ace Zones Pro Soccer Goalie Gloves. Evo Zone Technology delivers superior catching and control so you can dominate the game from the net. The negative cut ensures a snug feel while seamless touch features deliver breathability through the latex and foam construction. A stretch-strap wraps your hand to complete the gloves with a comfortable fit.', 114.99));
item_list.push(new Item('soccergear', 'Storelli Exoshield Goalie Jersey', 'Block kicks to the net with maximum mobility in the Storelli® Exoshield GK Adult Goalie Gladiator Jersey. This jersey withstands impact between the posts with polyurethane foam protection at the elbows. For increased comfort, the compression material wicks moisture away to keep the skin cool and dry. Dive and defend without distraction in the lightweight Storelli® Exoshield GK Adult Goalie Gladiator Jersey.', 64.99));
item_list.push(new Item('soccergear', 'Storelli BodyShield Slider Shorts', "Enjoy superior protection with the classic fit of the Storelli® sliders. Lightweight foam padding delivers high-performance protection to keep you safe from impact, swelling and cuts, while the unique design lets you freely move while the pads stay in place. Stay safe on the field with the antimicrobial technology and lightweight padding of the Storelli® Men's Slider Shorts.", 59.99));
item_list.push(new Item('soccergear', 'Adidas Estadio Teamp Backpack', 'Transport your gear to and from the field in style with the adidas® Estadio Team Backpack II. Built with soccer in mind, this backpack is constructed with multiple compartments to conveniently organize and store all of your gear. LoadSpring™ technology adds comfort to the shoulder straps so you can carry more equipment. FreshPAK™ shoe compartment keeps gear fresh throughout the season.', 55.00));
//add videogames
item_list.push(new Item('videogames', 'Star Wars Battlefront', 'Visit classic planets from the original Star Wars™ trilogy, detailed with an unprecedented amount of realism and sense of authenticity that will transport you to a galaxy far, far away', 59.99));
item_list.push(new Item('videogames', 'Just Cause 3', "The Mediterranean republic of Medici is suffering under the brutal control of General Di Ravello, a dictator with an insatiable appetite for power. Enter Rico Rodriguez, a man on a mission to destroy the general's ambitions by any means necessary. With more than 400 square miles of complete freedom from sky to seabed, and a huge arsenal of weaponry, gadgets and vehicles, prepare to unleash chaos in the most creative and explosive ways you can imagine.", 59.99));
item_list.push(new Item('videogames', 'Call of Duty Black Ops III', 'Call of Duty: black Ops III is the ultimate 3-games-in-1 experience. The Campaign you must navigate the hot spots of a new Cold War to find your missing brothers. Multiplayer features a new momentum-based chained movement system, allowing players to fluidly move through the environment with finesse. No Treyarch title would be complete without its signature Zombies offering "Shadows of Evil" has its own distinct storyline right out of the box.', 59.99));
item_list.push(new Item('videogames', 'Fallout 4', 'The epic storylines, adrenaline-pumping action and explosive thrills are back. The Fallout franchise returns with Fallout 4. Grab your controller and get ready to dive back into the enveloping storyline of this legendary series.', 59.99));
item_list.push(new Item('videogames', 'Halo 5: Guardians', 'A mysterious and unstoppable force threatens the galaxy, the Master Chief is missing and his loyalty questioned. Experience the most dramatic Halo story to date in a 4-player cooperative epic that spans three worlds. Challenge friends and rivals in new multiplayer modes: Warzone, massive 24-player battles, and Arena, pure 4-vs-4 competitive combat.*', 59.99));
item_list.push(new Item('videogames', "Assassin's Creed Syndicate", "WELCOME TO THE FAMILY — London, 1868. The Industrial Revolution fattens the purses of the privileged while the working class struggles to survive — until two Assassins rise to lead the world's first organized crime family. Conquer the streets of London. Bring the ruling class to their knees. Make history in a visceral adventure unlike any game you've played before.", 59.99));
// display item list
displayAll();
//When a new category is chosen it will correct and display items of that category type
$('#category').on('change', function(){
// read the selected category using 'value' attribute
var category = $(this).val();
if (category == '0')
displayAll(); // display all items
else
displaySelectedItems(category); // display selected items
});
//When category is chosen, items with the same type will be displayed
function displaySelectedItems(category){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
*/
for (var i=0; i<item_list.length; i++){
// display only selected items
if (item_list[i].type == category){
itemInfo += createItemData(item_list[i], i);
}
// add each item to the table
$('#item-list').html(itemInfo);
}
}
//Displays the item list
function displayAll(){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
Each element is an object.
*/
for (var i=0; i<item_list.length; i++){
// use each item to create HTML content
itemInfo += createItemData(item_list[i], i);
// add each item to the table
$('#item-list').html(itemInfo);
}
}
//Creates the item's data
function createItemData(item, index){
var trow = "<tr class='itemlist data-index='" +index+ "' >";
trow += "<td class=item-title'>"+item.title + "</td>";
trow += "<td class='item-description'>"+item.description + "</td>";
trow += "<td class='price'>$"+item.price + "</td>";
trow += "<td class='adding'><button type='button' class='addme' data- index='"+index+"'>Add</td></tr>";
return trow;
}
//Activates "Add" button so cart can be populated
$('#item-list').on('click', '.addme', function(){
// 1. Read the item index using data- attribute
var index = $(this).data('index');
if(!inCart(index)){
cart.push(index);
}
// 3. Update the cart list and total credits
displayCartItems();
checkCart();
// update price
calculateTotalPrice();
});
//function to check if items are in cart
function inCart(index){
for (var i=0; i<cart.length; i++){
if (cart[i] == index)
return true;
}
return false;
}
//Displays the shopping cart items
function displayCartItems(){
// create a table row for each item in cart array
var itemInfo = '';
for (var i=0; i<cart.length; i++){
var index = cart[i];
itemInfo += createTableRow(index);
}
$('#selected-list').html(itemInfo);
}
//Constructs the shopping cart table
function createTableRow(index){
var trow = '';
trow += "<tr><td>"+item_list[index].title + "</td>>";
trow += "<td id='itemsprice'>"+item_list[index].price + "</td>";
trow += "<td><select class='item-quantity' data-quantity='"+index+"'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option></td>";
trow += "<td id='tc-item'>"+item_list[index].price+"</td>"
trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
return trow;
}
//When quantity is changed change the value and compute new totals
$('#selected-list').on('change', '.item-quantity', function(){
calculateTotalPrice();
});
//If delete button is pressed in cart, the item is removed from the cart
$('#selected-list').on('click', '.delete-item', function(){
var index = $(this).val();
removeItemFromCart(index);
calculateTotalPrice();
checkCart();
});
function checkCart(){
if(cart.length == 0){
$('#empty-cart').html("Your cart is empty!");
} else {
$('#empty-cart').html("");
}
}
//function to remove items from the shopping cart
function removeItemFromCart(index){
// identify and remove the index from the cart and redisplay cart table
var pos = -1;
for (var i=0; i<cart.length; i++){
if (index == cart[i]){
pos = i;
break;
}
}
if (pos>-1){
cart.splice(pos, 1);
// reset the cart table
displayCartItems();
} else {
alert("Could not find!");
}
}
function calculateTotalPrice(){
var quantity = $('.item-quantity').val();
var subtotal = 0;
var tax = 0;
var shipping = 0;
var total = 0;
//for loop to calculate the subtotal
for(var i = 0; i < cart.length; i++){
var productPrice = item_list[cart[i]].price;
subtotal += productPrice * quantity;
}
//Percent taxed is 6%
var taxPerc = .06;
//Calculating taxes
tax = subtotal * taxPerc;
//Percent for shipping is 2%
var shippingPerc = .02;
//Calculating shipping
shipping = subtotal * shippingPerc;
//Calculating total
total = subtotal + tax + shipping;
//Displaying totals
//$('#tc-item').html(totalItemPrice.toFixed(2));
$('#subtotal').html(subtotal.toFixed(2));
$('#tax').html(tax.toFixed(2));
$('#shipping').html(shipping.toFixed(2));
$('#total').html(total.toFixed(2));
}
//Activates the Display cart and Hide cart buttons in shopping cart
$('#show-cart').on('click', function(){
$('#selected-list').show();
});
$('#hide-cart').on('click', function(){
$('#selected-list').hide();
});
});
</script>
</head>
<body>
<div class='container'>
<div class='row' id='top-box' >
<div class='col-sm-12'>
<h2>Sam's Discount Store</h2>
<h3>Variety of Items!</h3>
</div>
</div>
<div class='row' id='content'>
<div class='col-sm-8'>
<h3 class='title'>Discounted Items</h3>
<h4>
<select id='category'>
<option value='0' >All</option>
<option value='baseballgear' >Baseball Items</option>
<option value='soccergear' >Soccer Items</option>
<option value='videogames'>Video Games</option>
</select>
</h4>
<table class='table table-bordered clmlabels' >
<tr class='t-head'><td >Product</td>
<td >Description</td>
<td >Cost</td>
</tr>
<tbody id='item-list'>
</tbody>
</table>
</div>
<div class='col-sm-4'>
<h2>Cart Items</h2>
<p><button class='btn btn-primary' id='show-cart'>Display cart</button>
<button class='btn' id='hide-cart'>Hide cart</button></p>
<table class='table selected-list' id='selected-list'>
</table>
</div>
<table class='cart-table'>
<tr>
<td id='empty-cart'></td>
<tr>
<td>Subtotal: </td>
<td><span id='subtotal'>0</td>
</tr>
<tr>
<td>Tax: </td>
<td><span id='tax'>0</td>
</tr>
<tr>
<td>Shipping: </td>
<td><span id='shipping'>0</td>
</tr>
<tr>
<td>Total: </td>
<td><span id='total'>0</td>
</tr>
</table>
</div>
</div>
<div class='row' id='footer'
<div class='col-sm-12'> <p>Sam's Discount Store</p></div>
</div>
</div>
</body>
</html>
I have updated your code a bit. Now I think its working as expected. Please take a look at it.
Major change that I made is now instead of pushing only index into the cart array; I am now inserting quantity too like this:
cart.push({"index": index, "qty": 1});
Also whenever we change the quantity via select box; we are updating the number. And same value is getting used in total amount calculation.
I will suggest to compare below code with you local copy can see what all changes has been done. Hope it will help you.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sam's Discount Store </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<style type="text/css">
.courselist { cursor: pointer;}
.t-head { color: #fff; background-color: #333366; font-size: 20px; line- height: 20px; }
#top-box, #footer { background-color: #330066; color: #fff; text-align: center;}
#content {border: 1px solid #330099;}
</style>
<script>
$(function(){
/* The following function defines a constructor for creating an array of objects with four properties.
The keyword "this" refers to the instance of the object
*/
function Item(type,title,description,price){
this.type = type;
this.title = title;
this.description = description;
this.price = price;
}
//create an array to store items
var item_list = [];
var cart = []; //store index of elements in the shopping cart
//add items
//add baseballgear items
item_list.push(new Item('baseballgear','Louisville Slugger', 'The finest craftsmanship and finest materials ensure stepping to the plate with the Louisville Slugger® M9 Maple M110 Bat will allow you to swing what the pros swing.', 79.99 ));
item_list.push(new Item('baseballgear','Marucci Bat', 'Named for one of the most lethal hitters in the game, the Marucci® CUTCH22 Pro Model Baseball Bat features the same cut and finish swung by MLB® center fielder, Andrew McCutchen. The "Cutch" features a large, powerful, balanced barrel with a sleek cherry red and grey finish to deliver maximum performance at the plate. This adult wooden bat is also handcrafted and bone-rubbed to ensure superior quality and surface hardness.', 139.99));
item_list.push(new Item('baseballgear', 'Rawlings Glove', "Unrivaled quality season after season, the Rawlings® 11.25'' Pro Preferred® Series Glove returns to provide elite craftsmanship and superior performance for elite middle infielders.",349.99));
item_list.push(new Item('baseballgear', 'Wilson Glove', "Enhance your field performance with unrivaled dependability with the Wilson® 11.5 A2000™ Series Glove. Made with Pro Stock® leather for long-lasting performance, this glove's construction is preferred by professionals for its top-notch quality. Dri-Lex® technology in the wrist lining transfers moisture away from the skin to keep you cool and dry. The advanced design has been improved upon by the Wilson&Reg; Advisory Staff.",249.99 ));
item_list.push(new Item('baseballgear', 'Easton Baseball Helmet', 'Give your favorite player maximum protection at the plate with the Easton® Junior Z5 Elite Baseball Helmet. The ABS shell withstands impact and disperses energy away from the head, with a stylish Digi-Camo design. Featuring dual density foam liner for advanced comfort, this helmet boasts BioDri™ padded inner liner to wick moisture away from the skin to keep them cool and dry. Wrapped ear pads provide enhanced coverage around the head.', 54.99));
item_list.push(new Item('baseballgear', 'Rawlings Batting Gloves', 'Get the most out of your batting gloves this season with the Rawlings® Adult Workhorse 950 Batting Gloves. These gloves feature an Oiltac® leather palm pad to provide better grip and softness. Equipped with a Dura-Plus™ pad for added protection in the palm, the Dynamic Fit System™ provides greater comfort, flex, and feel during every play. The adjustable wrist closure is reinforced to provide a more secure fit', 34.99));
//add soccergear items
item_list.push(new Item('soccergear', 'Nike Ordem Soccer Ball', 'Hit the back of the net with the The Nike® Ordem 3 PL Soccer Ball. The Ordem 3 is the official match ball of the English Premier League for the 2015-2016 season. This FIFA® approved ball features Aerowtrac grooves and a micro-textured casing for accurate flight. The carbon latex bladder and fuse-welded construction allow for an exceptional touch while the vivid visual Power Graphics allow you to track the ball so you can react quickly.', 150.00));
item_list.push(new Item('soccergear', 'Wilson Shinguard', 'Maximize your protection for practice or game day with the Wilson® NCAA® Forte ll Soccer Shinguard. This high impact shinguard is constructed of a removable inner shell for adjustable protection to diffuse impact during elite-level play. Its Lycra® sleeve contains power band enhancements for added compression and blood circulation. Focus on your game with the Wilson® NCAA® Forte ll Soccer Shinguard.', 24.99 ));
item_list.push(new Item('soccergear', 'Adidas Goalie Gloves', 'Protect the goal line with intensity when you sport the adidas® Ace Zones Pro Soccer Goalie Gloves. Evo Zone Technology delivers superior catching and control so you can dominate the game from the net. The negative cut ensures a snug feel while seamless touch features deliver breathability through the latex and foam construction. A stretch-strap wraps your hand to complete the gloves with a comfortable fit.', 114.99));
item_list.push(new Item('soccergear', 'Storelli Exoshield Goalie Jersey', 'Block kicks to the net with maximum mobility in the Storelli® Exoshield GK Adult Goalie Gladiator Jersey. This jersey withstands impact between the posts with polyurethane foam protection at the elbows. For increased comfort, the compression material wicks moisture away to keep the skin cool and dry. Dive and defend without distraction in the lightweight Storelli® Exoshield GK Adult Goalie Gladiator Jersey.', 64.99));
item_list.push(new Item('soccergear', 'Storelli BodyShield Slider Shorts', "Enjoy superior protection with the classic fit of the Storelli® sliders. Lightweight foam padding delivers high-performance protection to keep you safe from impact, swelling and cuts, while the unique design lets you freely move while the pads stay in place. Stay safe on the field with the antimicrobial technology and lightweight padding of the Storelli® Men's Slider Shorts.", 59.99));
item_list.push(new Item('soccergear', 'Adidas Estadio Teamp Backpack', 'Transport your gear to and from the field in style with the adidas® Estadio Team Backpack II. Built with soccer in mind, this backpack is constructed with multiple compartments to conveniently organize and store all of your gear. LoadSpring™ technology adds comfort to the shoulder straps so you can carry more equipment. FreshPAK™ shoe compartment keeps gear fresh throughout the season.', 55.00));
//add videogames
item_list.push(new Item('videogames', 'Star Wars Battlefront', 'Visit classic planets from the original Star Wars™ trilogy, detailed with an unprecedented amount of realism and sense of authenticity that will transport you to a galaxy far, far away', 59.99));
item_list.push(new Item('videogames', 'Just Cause 3', "The Mediterranean republic of Medici is suffering under the brutal control of General Di Ravello, a dictator with an insatiable appetite for power. Enter Rico Rodriguez, a man on a mission to destroy the general's ambitions by any means necessary. With more than 400 square miles of complete freedom from sky to seabed, and a huge arsenal of weaponry, gadgets and vehicles, prepare to unleash chaos in the most creative and explosive ways you can imagine.", 59.99));
item_list.push(new Item('videogames', 'Call of Duty Black Ops III', 'Call of Duty: black Ops III is the ultimate 3-games-in-1 experience. The Campaign you must navigate the hot spots of a new Cold War to find your missing brothers. Multiplayer features a new momentum-based chained movement system, allowing players to fluidly move through the environment with finesse. No Treyarch title would be complete without its signature Zombies offering "Shadows of Evil" has its own distinct storyline right out of the box.', 59.99));
item_list.push(new Item('videogames', 'Fallout 4', 'The epic storylines, adrenaline-pumping action and explosive thrills are back. The Fallout franchise returns with Fallout 4. Grab your controller and get ready to dive back into the enveloping storyline of this legendary series.', 59.99));
item_list.push(new Item('videogames', 'Halo 5: Guardians', 'A mysterious and unstoppable force threatens the galaxy, the Master Chief is missing and his loyalty questioned. Experience the most dramatic Halo story to date in a 4-player cooperative epic that spans three worlds. Challenge friends and rivals in new multiplayer modes: Warzone, massive 24-player battles, and Arena, pure 4-vs-4 competitive combat.*', 59.99));
item_list.push(new Item('videogames', "Assassin's Creed Syndicate", "WELCOME TO THE FAMILY — London, 1868. The Industrial Revolution fattens the purses of the privileged while the working class struggles to survive — until two Assassins rise to lead the world's first organized crime family. Conquer the streets of London. Bring the ruling class to their knees. Make history in a visceral adventure unlike any game you've played before.", 59.99));
// display item list
displayAll();
//When a new category is chosen it will correct and display items of that category type
$('#category').on('change', function(){
// read the selected category using 'value' attribute
var category = $(this).val();
if (category == '0')
displayAll(); // display all items
else
displaySelectedItems(category); // display selected items
});
//When category is chosen, items with the same type will be displayed
function displaySelectedItems(category){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
*/
for (var i=0; i<item_list.length; i++){
// display only selected items
if (item_list[i].type == category){
itemInfo += createItemData(item_list[i], i);
}
// add each item to the table
$('#item-list').html(itemInfo);
}
}
//Displays the item list
function displayAll(){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
Each element is an object.
*/
for (var i=0; i<item_list.length; i++){
// use each item to create HTML content
itemInfo += createItemData(item_list[i], i);
// add each item to the table
$('#item-list').html(itemInfo);
}
}
//Creates the item's data
function createItemData(item, index){
var trow = "<tr class='itemlist data-index='" +index+ "' >";
trow += "<td class=item-title'>"+item.title + "</td>";
trow += "<td class='item-description'>"+item.description + "</td>";
trow += "<td class='price'>$"+item.price + "</td>";
trow += "<td class='adding'><button type='button' class='addme' data-index='"+index+"'>Add</td></tr>";
return trow;
}
//Activates "Add" button so cart can be populated
$('#item-list').on('click', '.addme', function(){
// 1. Read the item index using data- attribute
var index = $(this).data('index');
if(!inCart(index)){
cart.push({"index": index, "qty": 1});
}
// 3. Update the cart list and total credits
displayCartItems();
checkCart();
// update price
calculateTotalPrice();
});
//function to check if items are in cart
function inCart(index){
for (var i=0; i<cart.length; i++){
if (cart[i].index == index)
return true;
}
return false;
}
//Displays the shopping cart items
function displayCartItems(){
// create a table row for each item in cart array
var itemInfo = '';
for (var i=0; i<cart.length; i++){
var index = cart[i].index;
itemInfo += createTableRow(index);
}
$('#selected-list').html(itemInfo);
for (var i=0; i<cart.length; i++){
var index = cart[i].index;
var qty = cart[i].qty;
$("select#quantity_"+index).val(qty);
}
}
//Constructs the shopping cart table
function createTableRow(index){
var trow = '';
trow += "<tr><td>"+item_list[index].title + "</td>>";
trow += "<td id='itemsprice'>"+item_list[index].price + "</td>";
trow += "<td><select id='quantity_"+index+"' class='item-quantity' data-quantity='"+index+"'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option></td>";
trow += "<td id='tc-item'>"+item_list[index].price+"</td>"
trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
return trow;
}
//When quantity is changed change the value and compute new totals
$('#selected-list').on('change', '.item-quantity', function(){
var index = $(this).data("quantity");
for (var i=0; i<cart.length; i++){
if (index == cart[i].index){
cart[i].qty = parseInt($(this).val(),10);
}
}
calculateTotalPrice();
});
//If delete button is pressed in cart, the item is removed from the cart
$('#selected-list').on('click', '.delete-item', function(){
var index = $(this).val();
removeItemFromCart(index);
calculateTotalPrice();
checkCart();
});
function checkCart(){
if(cart.length == 0){
$('#empty-cart').html("Your cart is empty!");
} else {
$('#empty-cart').html("");
}
}
//function to remove items from the shopping cart
function removeItemFromCart(index){
// identify and remove the index from the cart and redisplay cart table
var pos = -1;
for (var i=0; i<cart.length; i++){
if (index == cart[i].index){
pos = i;
break;
}
}
if (pos>-1){
cart.splice(pos, 1);
// reset the cart table
displayCartItems();
} else {
alert("Could not find!");
}
}
function calculateTotalPrice(){
var subtotal = 0;
var tax = 0;
var shipping = 0;
var total = 0;
//for loop to calculate the subtotal
for(var i = 0; i < cart.length; i++){
var productPrice = item_list[cart[i].index].price;
var quantity = cart[i].qty;
subtotal += productPrice * quantity;
}
//Percent taxed is 6%
var taxPerc = .06;
//Calculating taxes
tax = subtotal * taxPerc;
//Percent for shipping is 2%
var shippingPerc = .02;
//Calculating shipping
shipping = subtotal * shippingPerc;
//Calculating total
total = subtotal + tax + shipping;
//Displaying totals
//$('#tc-item').html(totalItemPrice.toFixed(2));
$('#subtotal').html(subtotal.toFixed(2));
$('#tax').html(tax.toFixed(2));
$('#shipping').html(shipping.toFixed(2));
$('#total').html(total.toFixed(2));
}
//Activates the Display cart and Hide cart buttons in shopping cart
$('#show-cart').on('click', function(){
$('#selected-list').show();
});
$('#hide-cart').on('click', function(){
$('#selected-list').hide();
});
});
</script>
</head>
<body>
<div class='container'>
<div class='row' id='top-box' >
<div class='col-sm-12'>
<h2>Sam's Discount Store</h2>
<h3>Variety of Items!</h3>
</div>
</div>
<div class='row' id='content'>
<div class='col-sm-8'>
<h3 class='title'>Discounted Items</h3>
<h4>
<select id='category'>
<option value='0' >All</option>
<option value='baseballgear' >Baseball Items</option>
<option value='soccergear' >Soccer Items</option>
<option value='videogames'>Video Games</option>
</select>
</h4>
<table class='table table-bordered clmlabels' >
<tr class='t-head'><td >Product</td>
<td >Description</td>
<td >Cost</td>
</tr>
<tbody id='item-list'>
</tbody>
</table>
</div>
<div class='col-sm-4'>
<h2>Cart Items</h2>
<p><button class='btn btn-primary' id='show-cart'>Display cart</button>
<button class='btn' id='hide-cart'>Hide cart</button></p>
<table class='table selected-list' id='selected-list'>
</table>
</div>
<table class='cart-table'>
<tr>
<td id='empty-cart'></td>
<tr>
<td>Subtotal: </td>
<td><span id='subtotal'>0</td>
</tr>
<tr>
<td>Tax: </td>
<td><span id='tax'>0</td>
</tr>
<tr>
<td>Shipping: </td>
<td><span id='shipping'>0</td>
</tr>
<tr>
<td>Total: </td>
<td><span id='total'>0</td>
</tr>
</table>
</div>
</div>
<div class='row' id='footer'
<div class='col-sm-12'> <p>Sam's Discount Store</p></div>
</div>
</div>
</body>
</html>

Convert text to integer and if higher than 50 alert

On our current website that is hosted offsite via another company it is all done with .NET, I simply have access to HTML, JS, and CSS files to edit. A lot of data is output on the page via tokens. On our web page we have a weight token, it grabs the items weight and outputs it between a span tag. So if you're viewing the source it'll show the following:
<span id="order_summary_weight">78.000000 lbs</span>
The token by default outputs the lbs. What I need to do is have javascript grab the 78.000000, convert it to an integer I'm assuming and if that integer, in this case 78.000000 is greater than 50.000000 I'd like it append a line after the 78.000000 lbs to say "Your weight total is over 50 lbs, we will contact you directly with a shipping charge." Understand some weight totals may be as small as 0.010000
I'm coming to you fine folks here because I am at a complete lost where to start in this endeavor.
Something like this ? :
html :
<div class="wrap">
<span class="price" id="order_summary_weight">78.000000 lbs</span>
</div>
<hr>
<div class="wrap">
<span class="price" id="order_summary">50.000000 lbs</span>
</div>
JS :
$('.wrap').each(function(){
var price = $(this).find('.price').text();
price = price.replace(' lbs', '');
price = parseInt(price);
if(price > 50){
$(this).append('<div class="alert">Your weight total is over 50 lbs, we will contact you directly with a shipping charge.</div>');
}
});
DEMO : http://jsfiddle.net/w3qg4/1/
function getWeight()
{
var x=document.getElementById("order_summary_weight");
if(x > 50){
alert("Your weight total is over 50 lbs, we will contact you directly with a shipping charge. Understand some weight totals may be as small as 0.010000");
}
}

Categories