Run Jquery on multiple inputs

Asked

Viewed 46 times

1

How I would run jquery with multiple input fields to be changed?

I need to place the quantity of each product by clicking on .Minus and . plus

I have this HTML

<div class="quantity">
       <input type="button" value="+" class="plus">
       <input id="value" data-formid="" step="1" max="99" min="1" title="Qty" class="qty" type="number" name="prod[2385]" value="1" size="4">
       <input type="button" value="-" class="minus">
    </div>

    <div class="quantity">
       <input type="button" value="+" class="plus">
       <input id="value" data-formid="" step="1" max="99" min="1" title="Qty" class="qty" type="number" name="prod[2386]" value="1" size="4">
       <input type="button" value="-" class="minus">
    </div>

And that Jquery

$('.plus').click(function() { changeValue(1); });
$('.minus').click(function() { changeValue(-1); });

var formID=data("formid");

function changeValue(val) {
    var container = $('#value'+formID);
    var current = parseInt(container.val(), 10);
    container.val(Math.max(0, current + val).toString());
}

1 answer

2


I believe the script below meets what you want:

$('.plus').click(function() { 
   //Pega o valor do input que está na mesma div do botão clicado
   var valorAtual = parseInt($(this).closest('.quantity').find('[type=number]').val());
   //Atribui ao input o valor atual somando + 1
   if (valorAtual < 99){
       $(this).closest('.quantity').find('[type=number]').val(valorAtual + 1);
   }
});

$('.minus').click(function() { 
   //Pega o valor do input que está na mesma div do botão clicado
   var valorAtual = parseInt($(this).closest('.quantity').find('[type=number]').val());
   //Atribui ao input o valor atual subtraindo 1
   if (valorAtual > 1){
       $(this).closest('.quantity').find('[type=number]').val(valorAtual - 1);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="quantity">
       <input type="button" value="+" class="plus">
       <input id="value" data-formid="" step="1" max="99" min="1" title="Qty" class="qty" type="number" name="prod[2385]" value="1" size="4">
       <input type="button" value="-" class="minus">
    </div>

    <div class="quantity">
       <input type="button" value="+" class="plus">
       <input id="value" data-formid="" step="1" max="99" min="1" title="Qty" class="qty" type="number" name="prod[2386]" value="1" size="4">
       <input type="button" value="-" class="minus">
    </div>

Browser other questions tagged

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