Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 动态更改总计并显示它们_Javascript_Jquery_Html - Fatal编程技术网

Javascript 动态更改总计并显示它们

Javascript 动态更改总计并显示它们,javascript,jquery,html,Javascript,Jquery,Html,我正在使用html/javascript/jQuery制作一个程序,让用户检查购物车中想要的物品,然后计算小计、税费、运输成本和总额 现在我很难显示所有这些值,然后根据用户对数量的操作动态更改它们。此外,我有一个删除按钮,在我的购物车,如果这有任何关系 要指出您应该关注的内容,最有可能在函数中:calculateTotalPrice(),calculateSubtotal(),calculateTax(),calculateShipping(),calculateTotal(),或者在我试图修复

我正在使用html/javascript/jQuery制作一个程序,让用户检查购物车中想要的物品,然后计算小计、税费、运输成本和总额

现在我很难显示所有这些值,然后根据用户对数量的操作动态更改它们。此外,我有一个删除按钮,在我的购物车,如果这有任何关系

要指出您应该关注的内容,最有可能在函数中:
calculateTotalPrice()
calculateSubtotal()
calculateTax()
calculateShipping()
calculateTotal()
,或者在我试图修复数量动态输入的部分,这里为您准备:

$("#quantity").change(function(){
    calculateTotalPrice();

});
另一件事,当您检查项目并将其放入购物车时,输出如下所示:

小计:0.00

税:0.00

配送:0.00

Total:NaN

function calculateTotalPrice(){
    calculateSubtotal();
    calculateTax();
    calculateShipping();
    calculateTotal();
}
编辑:我将我的
calculateSubtotal()
函数更改为使用.each方法,而不是可能存在问题的for循环思维。我不再得到
Total:NaN
,它只是保持为
0
。我不知道这是否是一种进步,但我做出了改变

function calculateSubtotal(){
    var subtotal = 0;
    var quantity = 1;
    /*for(var i = 0; i < cart.lengh; i++){
        quantity = parseInt($(this).val());
        subtotal += parseInt(item_list[cart[i]].price * quantity);
    }*/

    $.each(cart, function(index){
        quantity = parseInt($(this).val());
        subtotal += parseInt(item_list[cart[index]].price * quantity);

    });

    $('#subtotal').html(subtotal.toFixed(2));

}

function calculateTax(){
    var taxAmount = 0;
    var taxes = .06;
    var subtotal = $('#subtotal').val();

    taxAmount = parseInt(subtotal * taxes);

    $('#tax').html(taxAmount.toFixed(2));
}


function calculateShipping(){
    var shippingAmount = 0;
    var shippingPerc = .02;
    var subtotal = $('#subtotal').val();

    shippingAmount = parseInt(subtotal * shippingPerc);

    $('#shipping').html(shippingAmount.toFixed(2));
}



function calculateTotal(){
    var totalCost = 0;
    var subtotal = $('#subtotal').val();
    var taxes = $('#tax').val();
    var shippingCost = $('#shipping').val();

    totalCost = parseInt(subtotal + taxes + shippingCost);

    $('#total').html(totalCost.toFixed(2));
}
函数calculateSubtotal(){
var小计=0;
变量数量=1;
/*对于(变量i=0;i
以下是完整的代码:

 <!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>UWW Semester Planner </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();
 $('#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

// Check all the selected items in the cart
checkCartElements();
 });

 function checkCartElements(){
    $('.addme').each(function(){ // do something with each checkbox
        // read its index
        var index = $(this).data('index');
        // check if the item with a selected index is in the cart
        var check = inCart(index); // returns true/false
        if(check == true){
            $(this).prop('checked', true);
        } else {
            $(this).prop('checked', false);
        }
    });
 }

 function inCart(index){
    for (var i=0; i<cart.length; i++){
        if (cart[i] == index)
            return true;
    }
    return false;
 }
 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);
     }
  }
 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); 
  }
 }

 function createItemData(item, index){
     /* Use the data-attribute to add the index of each element of the     array so that each checkbox can be mapped to
       the corresponding item. Then we can directly use the array of item    objects to prepare a suitable
    HTML structure and add to the shopping cart.
    */
    var trow = "<tr class='itemlist  data-index='" +index+ "' >";
        trow +=  "<td class=item-title'><input type='checkbox'   class='addme' data-index='"+ index +"' > "+item.title + "</td>";
        trow += "<td class='item-description'>"+item.description + "</td>";
        trow += "<td class='price'>"+item.price + "</td></tr>";
    return trow;
}




$('#item-list').on('click', '.addme', function(){
/* Whenever a item is selected by clicking on any of the checkboxes, perform the following: */   

 // 1. Read the item index using data- attribute
  var index = $(this).data('index');

 // 2. If the checkbox is checked then add the item to the cart. Else, remove it from the cart
 if ($(this).prop('checked')){
    cart.push(index);   
 } else {
    removeItemFromCart(index);
 }
 // 3. Update the cart list and total credits
    displayCartItems();

    // update price
    calculateTotalPrice();
});

$('#selected-list').on('click', '.delete-item', function(){
    var index = $(this).val();

    removeItemFromCart(index);
    calculateTotalPrice();
    checkCartElements();

});

$("#quantity").change(function(){
    calculateTotalPrice();

});

function calculateTotalPrice(){
    calculateSubtotal();
    calculateTax();
    calculateShipping();
    calculateTotal();
}

function calculateSubtotal(){
    var subtotal = 0;
    var quantity = 1;
    for(var i = 0; i < cart.lengh; i++){
        quantity = parseInt($(this).val());
        subtotal += parseInt(item_list[cart[i]].price * quantity);
    }

    $('#subtotal').html(subtotal.toFixed(2));

}

function calculateTax(){
    var taxAmount = 0;
    var taxes = .06;
    var subtotal = $('#subtotal').val();

    taxAmount = parseInt(subtotal * taxes);

    $('#tax').html(taxAmount.toFixed(2));
}

function calculateShipping(){
    var shippingAmount = 0;
    var shippingPerc = .02;
    var subtotal = $('#subtotal').val();

    shippingAmount = parseInt(subtotal * shippingPerc);

    $('#shipping').html(shippingAmount.toFixed(2));
}

function calculateTotal(){
    var totalCost = 0;
    var subtotal = $('#subtotal').val();
    var taxes = $('#tax').val();
    var shippingCost = $('#shipping').val();

    totalCost = parseInt(subtotal + taxes + shippingCost);

    $('#total').html(totalCost.toFixed(2));
}
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 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);
}

function createTableRow(index){
    var trow = '';
    trow+= "<tr><td>"+item_list[index].title + "</td>>";
    trow += "<td>"+item_list[index].price + "</td>";
    trow += "<td><input type='text' id='quantity' value='1'  size='5' />";
    trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
    return trow;
}

$('#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>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>

UWW学期计划员
.courselist{cursor:pointer;}
.t-head{color:#fff;背景色:#333366;字体大小:20px;行高:20px;}
#顶部框,#页脚{背景颜色:#330066;颜色:#fff;文本对齐:居中;}
#内容{边框:1px实心#330099;}
$(函数(){
/*以下函数定义了一个构造函数,用于创建具有四个属性的对象数组。
关键字“this”指的是对象的实例
*/
功能项(类型、标题、说明、价格){
this.type=type;
this.title=标题;
this.description=描述;
这个价格=价格;
}
//创建一个数组来存储项目
var项目清单=[];
var cart=[];//在购物车中存储元素索引
//添加项目
//添加基本装备项目
物品清单。推(新物品(‘棒球装备’、‘路易斯维尔击球手’、‘最好的工艺和最好的材料确保使用路易斯维尔击球手®M9枫木M110球拍踏上篮板,让你挥动职业选手挥动的东西’,,79.99));
项目列表。推(新项目(‘棒球装备’、‘Marucci球棒’,‘以比赛中最致命的击球手之一命名),Marucci®CUTCH22职业棒球模型球棒采用MLB®中外野手Andrew McCutchen挥动的相同切角和终点。“Cutch”采用大而有力、平衡的枪管,采用光滑的樱桃红和灰色饰面,在板上提供最佳性能。这种成年木蝙蝠还采用手工制作和骨摩擦,以确保卓越的质量和表面硬度。”,139.99);
物品清单。推送(新物品(‘棒球装备’、‘罗林斯手套’、‘品质无可匹敌的一季又一季,罗林斯®11.25’、‘Pro Preferred®系列手套回归,为精英中内野手提供精英工艺和卓越性能’,,349.99));
项目列表。推送(新项目('baseballgear','Wilson手套',“使用Wilson®11.5 A2000以无与伦比的可靠性增强您的现场性能™ 系列手套。采用Pro Stock®皮革制成,性能持久,专业人士首选该手套的结构,因为它具有一流的质量。手腕衬里中的Dri-Lex®技术可将水分从皮肤中转移出去,使您保持凉爽和干燥。高级设计经Wilson&Reg;咨询人员改进。”,249.99);
项目列表。推送(新项目(“baseballgear”、“Easton棒球头盔”、“Easton®Junior Z5 Elite棒球头盔”为您最喜爱的球员提供最大程度的保护。ABS外壳可承受冲击,并将能量分散到头部,采用时尚的Digi Camo设计。双密度泡沫衬里带来高级舒适感,这款头盔拥有BioDri™ 软垫内衬可吸走皮肤上的水分,保持皮肤凉爽干燥。包好的耳垫可增强头部周围的覆盖效果。”,54.99);
物品清单。推送(新物品('baseballgear','Rawlings击球手套','Rawlings成人Workhorse 950击球手套本季充分利用你的击球手套。这些手套采用Oiltac®皮革掌垫,提供更好的抓地力和柔软度。配备Dura Plus™ Dynamic Fit动态贴合系统为手掌提供额外保护™ 在每次比赛中提供更大的舒适度、柔韧性和手感。可调节腕部闭合装置经过加固,提供更安全的贴合感(34.99%);
//添加足球装备项目
物品列表。推送(新物品(‘足球装备’、‘Nike Ordem足球’、‘用Nike®Ordem 3 PL足球击打球网的背面’)
function createTableRow(index){
    var trow = '';
    trow+= "<tr><td>"+item_list[index].title + "</td>>";
    trow += "<td>"+item_list[index].price + "</td>";
    trow += "<td><input type='text' id='quantity' value='1'  size='5' />";
    trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
    return trow;
}
$("#quantity").change(function(){ calculateTotalPrice(); });
function createTableRow(index){
    var trow = '';
    trow+= "<tr><td>"+item_list[index].title + "</td>>";
    trow += "<td>"+item_list[index].price + "</td>";
    trow += "<td><input type='text' class='quantity' value='1'  size='5' />";
    trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
    return trow;
}

$('#selected-list').on("change", ".quantity", calculateTotalPrice);