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!
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);
}
});
You can add 'change' event listener to this button:
let totalItems = $('#total_items');
totalItems.change(function () {
if (totalItems.val() == 0) {
totalItems.hide();
}
else totalItems.show();
});
Also you should trigger this event in your success method of ajax:
success: function(response) {
document.getElementById("total_items").value = response;
totalItems.change();
}
And finally hide this button at start:
<input type="button" id="total_items" value="0" style="display: none">
Check this working in fiddle: https://jsfiddle.net/xpvt214o/771844/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.