0

Suppose I have the following code:

{% for i in range(43) %}
<div class="col-sm-6 col-md-4 col-xl-3 col-lg-3 my-2 d-flex">
<div class="card h-100">
<img src="/static/images/khaltat_1 ({{ i + 1 }}).jpeg" class="card-img-top h-80" 
alt="Perfume">
<div class="card-body flex-fill">
<input type="hidden" value="{{ i + 1 }}" name="id">
</div>
  <div class="card-title px-2">Price: BD5</div><h5 class="px-2">60ML</h5>
  <input type="hidden" value="{{ i + 1 }}" name="id">
  <select class="form-select" aria-label="Default" name="counts">
  <option selected value="1">quantity</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  </select>
  <button type="button" class="btn btn-success" id="button">Add To Cart</button>   
</div>
</div>
{% endfor %}
-------------------------------JavaScript----------------------------
<script>
            $(function() {
            $("button").on("click", function() {
            $.ajax({
                method: "POST",
                url: "cart",
                data: {id:$('input[name="id"]').val(), 
                      counts:$('select[name="counts"]').val()},
                success: function(data, status, xhr) {
                    console.log(data);
                },
                error: function(x,s,err) {
                    console.log(err);
                }
                });
            });
        });
    </script>

And I am using ajax to submit the specific item to the cart when the button clicked

this code return the first input field in the page, How can I make it gives the nearest field?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ali Saleh
  • 23
  • 4

1 Answers1

2

Use siblings() to get elements that are children of the same DIV.

data: {
    id: $(this).siblings('input[name="id"]').val(), 
    counts: $(this).siblings('select[name="counts"]').val()
},
Barmar
  • 741,623
  • 53
  • 500
  • 612