3
I have a $(".btn-buy") function. click() which, when I click, runs twice. I can’t solve the problem. I’ve already searched the whole code and it doesn’t have duplicity. Which could be?
Function:
$(".btn-comprar").click(function () {
var produto = {};
produto.nome = $(this).parent().find('h3').text();
produto.valor = $(this).parent().find('.preco').text();
produto.quantidade = $(this).parent().find('input').val();
produto.id = $(this).parent().find('input').attr('data-button');
if (sessionStorage) {
var cart = JSON.parse(sessionStorage.getItem('cart'));
cart.produtos.push(produto);
$(".numCart").text(cart.produtos.length);
sessionStorage.setItem('cart', JSON.stringify(cart));
alert('Produto adicionado ao carrinho.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class='btn btn-comprar' href='javascript:'>Comprar</a>
Check if the . btn-buy class is being used in other elements.
– diegofcruz
There are other elements that use the class, because it is a buy button, common to all products of the page. But it is only executed when the user clicks.
– michelmfreitas
Try to place the e.preventDefault(); before the product var = {};
– pho3nix