dongyu7074 2018-09-11 02:13
浏览 76

如果购物车中没有商品,请隐藏AJAX购物车商品编号

I'm struggling with some javascript to figure out the proper way to make it work.

I have a button showing the number of items in the cart. By default is zero. As items added the cart the number is increasing. But at the beginning, I don't want to show "0" in the cart.

HTML:

<p id="cart_button" onclick="show_cart();">
  <input type="button" id="total_items" value="0">
</p>

<div id="mycart"></div>

<div id="item_div">

  <div class="items" id="item1">
    <input type="button" value="Add To CART" onclick="cart('item1')">
    <p>Simple Navy Blue T-Shirt</p>
    <input type="hidden" id="item1_name" value="ITEM-ID1">
  </div>

  <div class="items" id="item2">
    <input type="button" value="Add To CART" onclick="cart('item2')">
    <p>Trendy T-Shirt With Back Design</p>
    <input type="hidden" id="item2_name" value="ITEM-ID2">
  </div>

</div>

JAVASCRIPT:

$(document).ready(function() {

  $.ajax({
    type: 'post',
    url: 'store_items.php',
    data: {
      total_cart_items: "totalitems"
    },
    success: function(response) {
      document.getElementById("total_items").value = response;
    }
  });
});

function cart(id) {
  var name = document.getElementById(id + "_name").value;

  $.ajax({
    type: 'post',
    url: 'store_items.php',
    data: {
      item_name: name
    },
    success: function(response) {
      document.getElementById("total_items").value = response;
    }
  });
}

function show_cart() {
  $.ajax({
    type: 'post',
    url: 'store_items.php',
    data: {
      showcart: "cart"
    },
    success: function(response) {
      document.getElementById("mycart").innerHTML = response;
      $("#mycart").slideToggle();
    }
  });
}

I basically want the button with 0 to be hidden until it gets a value. if it goes back to zero I want it to be hidden again. Thank you for the help!

  • 写回答

2条回答 默认 最新

  • dsigg21445 2018-09-11 02:18
    关注

    You can show/hide when update cart:

    // Add this function
    function update_cart(value) {
      document.getElementById("total_items").value = response;
    
      if (value > 0) {
        // Show the cart
        document.getElementById("total_items").style.display = "block";
      } else {
        // Hide the cart
        document.getElementById("total_items").style.display = "none";
      }
    }
    

    Then, you need to change your code, when update cart:

    $.ajax({
      type: 'post',
      url: 'store_items.php',
      data: {
        total_cart_items: "totalitems"
      },
      success: function(response) {
        update_cart(response);
      }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持