Link to home
Create AccountLog in
Avatar of Richard Lloyd
Richard Lloyd

asked on

How to select which input field is related to a button with Ajax form

I have a shopping cart that displays a grid of products on a single page. Each product has an input number field to capture the quantity required and an "Add to cart"/ "Update cart" button.

The input number fields each have a class of "product_qty" and an id of "qty_x" and where X is the unique id of the product. The add/update buttons have id "btn_x" and class of "update_cart".

Please can any advise how I can make sure I pass the correct value from the product quantity input to my Ajax form when I click the "Add to cart" button on a particular product.

I sort of need to "link" the input field to the button on each product, in a traditional form, the input and button would be contained within a <form></form>, but I am not sure how to do this in Ajax.

Thank you
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Vanilla JS or jQuery ?
Could you share the generated HTML of the grid ?

Avatar of Richard Lloyd
Richard Lloyd

ASKER

Hi

Jquery...

Sample of 2 items:

Line wrap

<div class='card'>

    <div class='card-body text-center'>

        <h3 class='card-title text-center'>Charcoal</h3>

        <p>Sustainable Lumpwood Charcoal 2.25kg</p>

        <h4 class='text-center'>&pound;9.45</h4>

        <div class='card-footer'>

            <p><input type='number' class='updatecart' id='qty_500' value='' min='0' max='33' /></p>

            <p style='text-align:center'><button class='btn btn-primary update_cart' id='btn_500'>Add to cart</button></p>

        </div>

    </div>

</div>

<div class='card'>

    <div class='card-body text-center'>

        <h3 class='card-title text-center'>Kindling Nets</h3>

        <p>Our Kindling</p>

        <h4 class='text-center'>&pound;6.30</h4>

        <div class='card-footer'>

            <p><input type='number' class='updatecart' id='qty_495' value='' min='0' max='599' /></p>

            <p style='text-align:center'><button class='btn btn-primary update_cart' id='btn_495'>Add to cart</button></p>

        </div>

    </div>

</div>
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Great. Thank you.

I'll try it and confirm.