Implementation of shopping cart function based on JavaScript

  • 2021-07-18 06:29:56
  • OfStack

In this paper, we share the specific code of js shopping cart function for your reference, the specific contents are as follows


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<div id="shop">
  <button id="btAdd"> My shopping cart </button><br><br>

  <table id="cart">
    <thead>
    <tr>
      <th> Unit price </th>
      <th> Quantity </th>
      <th> Subtotal </th>
      <th> Operation </th>
    </tr>
    </thead>
    <tbody>

    </tbody>
    <tfoot>
    <tr>
      <td colspan="4"> Total amount of shopping cart: <span id="total">0.00</span></td>
    </tr>
    </tfoot>
  </table>
</div>
<div id="footer"></div>
<script>
  $('#read .page li a').click(function(){
    var n=$(this).html();

    $(this).parent().parent().next().children('p:nth-child('+n+')').slideDown(2000);
    $(this).parent().parent().next().children('p:nth-child('+n+')').siblings().css('display','none');
  })

  $('#btAdd').click(function(){
    var p = randPrice();
    var c = randCount();
    $('#cart tbody').append('<tr>'+
      '<td>'+p+'</td>'+
      '<td><input type="text" value="'+c+'"></td>'+
      '<td>'+parseFloat((p*c).toFixed(2))+'</td>'+
      '<td><a href="#" rel="external nofollow" >&times;</a></td>'+
      '</tr>');
    $('#total').html( getTotal() );
  });

  // For the Delete button ( I.e. X No. ) Bind the event listener function, note: X Is added later, a lot X The behavior performed is 1 Sample-using event brokers 
  $('#cart tbody').delegate('td > a', 'click',function(event){
    event.preventDefault();
    var a = event.target;
    $(a).parent().parent().remove();

  });
  // Do event binding for the "Purchase Quantity" input box-use event broker 
  $('#cart tbody').delegate('td > input','change', function(event){

    var input = event.target;
    var count = input.value;
    var price = $(input).parent().prev().html();
    $(input).parent().next().html( price*count );
    $('#total').html( getTotal() );
  })
  // Calculate the total amount of shopping cart 
  function getTotal(){
    var sum = 0;
    $('#cart tbody tr td:nth-child(3)').each(function(i, td){
      sum += parseInt(td.innerHTML);
    })
    return sum;
  }


  function randPrice(){
    var p = Math.random()*100;
    p = p.toFixed(2);
    p = parseFloat(p);
    return p;
  }
  function randCount() {
    var c = Math.floor(Math.random() * 10 + 1);
    return c;

  }
  $('#header').load('php/header.php');
  $('#footer').load('php/footer.php');
  var theme=localStorage.getItem('ChoseTheme');
  applyTheme(theme)

</script>

</body>
</html>


Related articles: