0

I am trying to add a number indicator to my cart icon that will display the number of items added after the product has been saved to my database.

<div class="main__section-content">
               <% if( allProd.length > 0 ) {%>

                <% for(product of allProd){%>
                    <article class="main__section-card">
                        <img src="<%= product.imageUrl %>" alt="<%= product.title %>" class="card-img">
                        <section class="card-container">
                            <h4><%= product.title %> </h4>
                            <p>$ <%= product.price %></p>
                            <form action="/cart" method="post" class="card-form">
                                <input type="hidden" name="productId" value="<%= product._id %>">
                                <button class="card-btn" type="submit" >Add to cart</button>
                            </form>
                        </section>
                    </article>
                    <%} %>
                <%} %>
            </div>

I am trying to attach an eventlistener to all

Add to cart button

 const addToCartBtn = document.querySelectorAll('.card-btn');
    addToCartBtn.forEach(btn => {
        btn.addEventListener('click', (e)=>{
      e.preventDefault();     
 console.log('btn');
        })
    });

nothing comes out of the console before the post request is sent.

this is how i handle the post request

exports.postCart = (req, res) => {
    const prodId = req.body.productId;
    Product.findById(prodId)
    .then(product =>{
        return req.user.addToCart(product);
    })
    .then(result => {
        console.log(result);
        res.redirect('/')
    }).catch(err => console.log(err));
};

please help!

Hope007
  • 1
  • 2
  • 1
    `nothing comes out of the console before the post request is sent.` because a form submit loads a **new page** - you need to **prevent** the **Default** action of a form submit if you don't want this to happen – Bravo Apr 08 '22 at 01:02
  • Buttons don't emit _submit_ events either – Phil Apr 08 '22 at 01:03
  • I have prevented the default and remove the route still it not working. sorry if this sounds dumb but if I don't submit the form how will I save the product into my database. – Hope007 Apr 08 '22 at 01:47
  • @Phil my bad, I have edited it – Hope007 Apr 08 '22 at 01:50
  • Can't see where you're preventing the default action. What is it exactly you want to do with this code? You can either submit the form normally or intercept the event with JS. If the latter, you can always submit the form programatically or fire off an async request – Phil Apr 08 '22 at 01:57
  • @Phil so I wasn't clear before, this is just a demo. I'm trying to attach a click eventlistener to every button with a function that indicate the number of time the button is click. – Hope007 Apr 08 '22 at 10:51

0 Answers0