Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
How to get the closets input field to the clicked button in JavaScript OR Jquery?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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()
},
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda