Pick up specific input value with the click of the button

Asked

Viewed 1,138 times

0

Good morning, I’m stuck in an issue in my code where I have several buttons and inputs type "number" on the same page and with the click of the button, adds x times (input value) the specific product in the shopping cart.

<input type="number" class="quantidade" value="1" data-quantity="{{ product.id }}">
<input type="button" id="{{ product.id }}" value="Comprar"  onclick="addCart()">

I thought of creating a "data-Quantity" attribute in input with the product id I get via Twig and compare it with the button id which is the product id itself. However, how do I do this verification via Javascript now? I’m trying so.

function addCart(product_id){
    var botao = $('#{{ product.id }}');
    var entrada = $('.quantidade');

    if (botao.attr('id') == entrada.attr('data-quantity')) {
        var quantidade = entrada.val();
        console.log(quantidade); //Deve imprimir a quantidade do input referente ao botão apertado.

        // Aqui eu envio o valor da variável quantidade via ajax, o que não é problema depois que conseguir armazenar esse valor.
    }
}
  • Put in the question the HTML of where the field is and the button that can be done in a much better and simpler way.

1 answer

2

In the example below I select the input directly by data-quantity, note that I pass the event to the function and from it extract the id of the button target.

https://api.jquery.com/attribute-equals-selector/

https://api.jquery.com/event.target/

function addCart(e){
    console.log(
      $('.quantidade[data-quantity="'+e.target.id+'"]').val()
    )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="quantidade" value="555" data-quantity="produto_1">
<input type="button" id="produto_1" value="Comprar"  onclick="addCart(event)">

EDIT:

Another way to do it is to pass the id directly to the function instead of the event, the result is the same:

function addCart(id){
    console.log(
      $('.quantidade[data-quantity="'+id+'"]').val()
    )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="quantidade" value="555" data-quantity="produto_1">
<input type="button" id="produto_1" value="Comprar"  onclick="addCart(this.id)">

  • It worked right here, but I did not understand the " step the event to the function and from it extract the id".

  • 1

    the Event variable that is passed loads the data from the click event... In this event there is an attribute target that references the button that was clicked. From that target(that is the button) I capture the id and use it in the selector.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.