Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Add to cart - avoid page refresh

I have the following setup: https://jsfiddle.net/uosLke60/

input.Add_To_Cart_Button {
  background-color: #000;
  color: #fff;
  border: none;
  font: inherit;
  cursor: pointer;
  font-size: 13px;
  margin-bottom: 40px;
  width: 120px;
  -webkit-appearance: none;
  border-radius: 0;
}
<div class="Product_Card_Button">
  <form method="post" action="/cart/add">
    <quantity-input class="quantity" style="width: 120px; min-height: 25.4px; display: inline-flex;">
      <button class="quantity__button no-js-hidden" name="minus" type="button"> - </button>
      <input class="quantity__input" type="number" name="quantity" id="quantity" min="1" value="1" style="text-align: center;">
      <button class="quantity__button no-js-hidden" name="plus" type="button">+</button>
    </quantity-input>
    <br>
    <input type="submit" value="Add to cart" class="Add_To_Cart_Button" />
  </form>
</div>

When the add to cart button is pressed, the page refreshes. How can I adjust it so that the product is added to cart without the page refresh? I have tried a number of jQuery solutions suggested in other posts but without any luck. Any suggestions would be helpful. Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should listen for the submit event on your form and:

  1. call event.preventDefault() which blocks the default action (in your case the form submit)
  2. return false, which ultimately cancels the event

I would do something like this


    function handleAddToCart(form) {
        const url = form.getAttribute("action");
      const formData = new FormData(form);
      doSomePost(url, formData);
    }
    
    // Cache this if possible
    document.querySelector("[add-to-cart-form]")
    .addEventListener("submit", (e) => {
        e.preventDefault();
      handleAddToCart(e.target);  
      return false;
    });

I updated your fiddle as well => fiddle

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda