Reputation: 45
I have a group of generated inputs with the task of adding items to a shop list and adding the value to a sessionStorage Key:
$('.increment').click(function increment() {
$('.quantity-input').val(function(i, oldval) {
return parseInt(oldval, 10) + 1;
});
});
$('.drecement').click(function increment() {
$('.quantity-input').val(function(i, oldval) {
return parseInt(oldval, 10) - 1;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter-container">
<input class="quantity-input" id="
<?php echo $id_produtos; ?>" type="text" value="1">
<div class="btn-container">
<button id="<?php echo $id_produtos; ?>" class="btn-arrow
increment">▲</button>
<button id="<?php echo $id_produtos; ?>" class="btn-arrow
drecement">▼</button>
</div>
</div>
<div class="counter-container">
<input class="quantity-input" id="
<?php echo $id_produtos; ?>" type="text" value="1">
<div class="btn-container">
<button id="<?php echo $id_produtos; ?>" class="btn-arrow
increment">▲</button>
<button id="<?php echo $id_produtos; ?>" class="btn-arrow
drecement">▼</button>
</div>
</div>
The problem is that I'm changing also the others generated inputs:
How can I ONLY change the input that I'm clicking?
Upvotes: 0
Views: 44
Reputation: 67525
You need to use $(this)
to refer to the related input by going up to the parent div using .closest('.counter-container')
then select the desired input using .find('.quantity-input')
like :
$(this).closest('.counter-container').find('.quantity-input').val(...
$('.increment').click(function increment() {
$(this).closest('.counter-container').find('.quantity-input').val(function(i, oldval) {
return parseInt(oldval, 10) + 1;
});
});
$('.drecement').click(function increment() {
$(this).closest('.counter-container').find('.quantity-input').val(function(i, oldval) {
return parseInt(oldval, 10) - 1;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter-container">
<input class="quantity-input" id="x_1" type="text" value="1">
<div class="btn-container">
<button id="1" class="btn-arrow increment">▲</button>
<button id="1" class="btn-arrow drecement">▼</button>
</div>
</div>
<div class="counter-container">
<input class="quantity-input" id="x_2" type="text" value="1">
<div class="btn-container">
<button id="y_2" class="btn-arrow increment">▲</button>
<button id="z_2" class="btn-arrow drecement">▼</button>
</div>
</div>
<div class="counter-container">
<input class="quantity-input" id="x_3" type="text" value="1">
<div class="btn-container">
<button id="y_3" class="btn-arrow increment">▲</button>
<button id="z_3" class="btn-arrow drecement">▼</button>
</div>
</div>
Upvotes: 2