计算复选框的总数

时间:2016-04-01 18:30:34

标签: javascript jquery performance javascript-events listener

我目前正在开发购物车,当消费者选择某些选项时,该购物车会自动计算总数。我目前卡在复选框上。我希望他们在检查后自动计算小计中的。正如您所看到的,它成功地计算了所有内容,直到您进入复选框。如果你能帮助我,我会非常感激。

PS:我是一个新秀



var removedItem,
    sum = 0;

$(function(){
  // calculate the values at the start
  calculatePrices();
  
  // Click to remove an item
  $(document).on("click", "a.remove", function() {
      removeItem.apply(this);
  });
  
  // Undo removal link click
  $(document).on("click", ".removeAlert a", function(){    
    // insert it into the table
    addItemBackIn();
    //remove the removal alert message
    hideRemoveAlert();
  });
  
  $(document).on("change", "input.quantity", function(){
    var val = $(this).val(),
        pricePer,
        total
    
    if ( val <= "0") {
      removeItem.apply(this);
    } else {
      // reset the prices
      sum = 0;
      
      // get the price for the item
      pricePer = $(this).parents("td").prev("td").text();
      // set the pricePer to a nice, digestable number
      pricePer = formatNum(pricePer);
      // calculate the new total
      total = parseFloat(val * pricePer).toFixed(2);
      // set the total cell to the new price
      $(this).parents("td").siblings(".itemTotal").text("$" + total);
      
      // recalculate prices for all items
      calculatePrices();
    }
  });
  
});


function removeItem() {
 // store the html
  removedItem = $(this).closest("tr").clone();
  // fade out the item row
  $(this).closest("tr").fadeOut(500, function() {
    $(this).remove();
    sum = 0;
    calculatePrices();
  });
  // fade in the removed confirmation alert
  $(".removeAlert").fadeIn();
  
  // default to hide the removal alert after 5 sec
  setTimeout(function(){
    hideRemoveAlert();
  }, 5000); 
}

function hideRemoveAlert() {
  $(".removeAlert").fadeOut(500);
}

function addItemBackIn() {
  sum = 0;
  $(removedItem).prependTo("table.items tbody").hide().fadeIn(500) 
  calculatePrices();
}

function updateSubTotal(){
  $("table.items td.itemTotal").each(function(){
    var value = $(this).text();
    // set the pricePer to a nice, digestable number
    value = formatNum(value);

    sum += parseFloat(value);
    $("table.pricing td.subtotal").text("$" + sum.toFixed(2));
  });
}

function addTax() {
  var tax = parseFloat(sum * 0.13).toFixed(2);
  $("table.pricing td.tax").text("$" + tax);
}

function calculateTotal() {
  var subtotal = $("table.pricing td.subtotal").text(),
      tax = $("table.pricing td.tax").text(),
      post = $("table.pricing td.post").text(),
      total;
  
  subtotal = formatNum(subtotal);
  tax = formatNum(tax);
  post = formatNum(post);
   
  total = (subtotal + tax + post).toFixed(2);
  
  $("table.pricing td.orderTotal").text("$" + total);
}

function calculatePrices() {
  updateSubTotal();
  addTax();
  calculateTotal();
}

function formatNum(num) {
  return parseFloat(num.replace(/[^0-9-.]/g, ''));
}
&#13;
<html >
  <head>
    <meta charset="UTF-8">
    <title>TITLE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
    <link rel="stylesheet" href="styles/cartnormalize.css">

    <link rel='stylesheet prefetch' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css'>

        <link rel="stylesheet" href="styles/cartstyle.css">
  </head>





  <body>

    <div class="content">
  <h1>Service Name</h1>
  
  <p class="removeAlert">
    Item has been removed. Made a mistake? <a href="#">Undo removal</a>
  </p>

  
  
<table class="items">
   <tbody>
      <tr>
        <td>
         <p>
            Amount
            <br />
          </p>
          <p class="description">The minimum amount allowed is $160.00</p>
        </td>


        <td>$1.00</td>



        <td>
          <input type="number" class="quantity" value="160" min="160" />
          <a href="#" class="remove">Remove</a>
        </td>
        <td class="itemTotal">$160.00</td>
      </tr>
</tbody>
  </table>

  <Fieldset>
<legend>Extra features</legend>
<p><input type="checkbox" name="featured" value="59.99"/> Featured Project ($59.99)</p>
<p><input type="checkbox" name="featured" value="99.99"/> Private project ($99.99)</p>
</fieldset>




  
  <div class="cost">
    <h2>Order Overview</h2>
    
    <table class="pricing">
      <tbody>
        <tr>
          <td>Subtotal</td>
          <td class="subtotal"></td>
        </tr>
        <tr>
          <td>13% Fee</td>
          <td class="tax"></td>
        </tr>
        <tr>
          <td>Post Fee</td>
          <td class="post">$99.99</td>
        </tr>
        <tr>
          <td><strong>Total:</strong></td>
          <td class="orderTotal"></td>
        </tr>
      </tbody>
    </table>
    
    <a class="cta" href="#">Checkout Now &raquo;</a>
  </div>
</div> <!-- End Content -->



    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>

    <script src="Scripts/Cart.js"></script>

    
    
    
  </body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

features上添加了一个事件监听器,它将总和加起来。

var removedItem,
    sum = 0;

$(function(){
  // calculate the values at the start
  calculatePrices();
  
  // Click to remove an item
  $(document).on("click", "a.remove", function() {
      removeItem.apply(this);
  });
  
  // Undo removal link click
  $(document).on("click", ".removeAlert a", function(){    
    // insert it into the table
    addItemBackIn();
    //remove the removal alert message
    hideRemoveAlert();
  });
  
  $(document).on("change", "input.quantity", function(){
    var val = $(this).val(),
        pricePer,
        total
    
    if ( val <= "0") {
      removeItem.apply(this);
    } else {
      // reset the prices
      sum = 0;
      
      // get the price for the item
      pricePer = $(this).parents("td").prev("td").text();
      // set the pricePer to a nice, digestable number
      pricePer = formatNum(pricePer);
      // calculate the new total
      total = parseFloat(val * pricePer).toFixed(2);
      // set the total cell to the new price
      $(this).parents("td").siblings(".itemTotal").text("$" + total);
      
      // recalculate prices for all items
      calculatePrices();
    }
  });
  
});


function removeItem() {
 // store the html
  removedItem = $(this).closest("tr").clone();
  // fade out the item row
  $(this).closest("tr").fadeOut(500, function() {
    $(this).remove();
    sum = 0;
    calculatePrices();
  });
  // fade in the removed confirmation alert
  $(".removeAlert").fadeIn();
  
  // default to hide the removal alert after 5 sec
  setTimeout(function(){
    hideRemoveAlert();
  }, 5000); 
}

function hideRemoveAlert() {
  $(".removeAlert").fadeOut(500);
}

function addItemBackIn() {
  sum = 0;
  $(removedItem).prependTo("table.items tbody").hide().fadeIn(500) 
  calculatePrices();
}

function updateSubTotal(){
  $("table.items td.itemTotal").each(function(){
    var value = $(this).text();
    // set the pricePer to a nice, digestable number
    value = formatNum(value);

    sum += parseFloat(value);
    $("table.pricing td.subtotal").text("$" + sum.toFixed(2));
  });
}

$('input:checkbox[name="featured"]').click(function(){
  sum = 0;    
  calculatePrices();
});

function checkForFeatures(){
  $('input:checkbox[name="featured"]').each(function(){
    var feature = $(this);
    if(feature.is(':checked')){
     sum += parseFloat(formatNum(feature.val()));
    }
  }); 
}

function addTax() {
  var tax = parseFloat(sum * 0.13).toFixed(2);
  $("table.pricing td.tax").text("$" + tax);
}

function calculateTotal() {
  var subtotal = $("table.pricing td.subtotal").text(),
      tax = $("table.pricing td.tax").text(),
      post = $("table.pricing td.post").text(),
      total;
  
  subtotal = formatNum(subtotal);
  tax = formatNum(tax);
  post = formatNum(post);
   
  total = (subtotal + tax + post).toFixed(2);
  
  $("table.pricing td.orderTotal").text("$" + total);
}

function calculatePrices() {
  checkForFeatures();
  updateSubTotal();
  addTax();
  calculateTotal();
}

function formatNum(num) {
  return parseFloat(num.replace(/[^0-9-.]/g, ''));
}
<html >
  <head>
    <meta charset="UTF-8">
    <title>TITLE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
    <link rel="stylesheet" href="styles/cartnormalize.css">

    <link rel='stylesheet prefetch' href='http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css'>

        <link rel="stylesheet" href="styles/cartstyle.css">
  </head>





  <body>

    <div class="content">
  <h1>Service Name</h1>
  
  <p class="removeAlert">
    Item has been removed. Made a mistake? <a href="#">Undo removal</a>
  </p>

  
  
<table class="items">
   <tbody>
      <tr>
        <td>
         <p>
            Amount
            <br />
          </p>
          <p class="description">The minimum amount allowed is $160.00</p>
        </td>


        <td>$1.00</td>



        <td>
          <input type="number" class="quantity" value="160" min="160" />
          <a href="#" class="remove">Remove</a>
        </td>
        <td class="itemTotal">$160.00</td>
      </tr>
</tbody>
  </table>

  <Fieldset>
<legend>Extra features</legend>
<p><input type="checkbox" name="featured" value="59.99"/> Featured Project ($59.99)</p>
<p><input type="checkbox" name="featured" value="99.99"/> Private project ($99.99)</p>
</fieldset>




  
  <div class="cost">
    <h2>Order Overview</h2>
    
    <table class="pricing">
      <tbody>
        <tr>
          <td>Subtotal</td>
          <td class="subtotal"></td>
        </tr>
        <tr>
          <td>13% Fee</td>
          <td class="tax"></td>
        </tr>
        <tr>
          <td>Post Fee</td>
          <td class="post">$99.99</td>
        </tr>
        <tr>
          <td><strong>Total:</strong></td>
          <td class="orderTotal"></td>
        </tr>
      </tbody>
    </table>
    
    <a class="cta" href="#">Checkout Now &raquo;</a>
  </div>
</div> <!-- End Content -->



    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>

    <script src="Scripts/Cart.js"></script>

    
    
    
  </body>
</html>