I have the following html in the dom:
<div id="quantity_1">
<button role="button"></button>
<span >Qty:</span>
<input type="number" min="0" size="2" name="updates[]" id="updates_33467117961304" value="1">
<button role="button"></button>
</div>
I need to get and adjust the value of .quantity but related to the parent since there is a several quantity elements in the dom (when multiple products are loaded).
My attempt is:
$('.qtyplus').on('click', function(e) {
var qtyId = $(this).parent().attr('id');
var qtyParent = '.' qtyId;
var qtyValClass = $(qtyParent).find('.quantity');
console.log(qtyValClass.val());
})
This returns undefined. I'm dong something wrong when trying to get the element but can't figure out what it is. Any idea?
CodePudding user response:
It is unnecessary to complicate the work using ID. This way you can make more specific uses.
$('.qtyplus').on('click', function(e) {
var quantity = $(this).closest('.quantity_control').find('.quantity').val();
console.log(quantity);
})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="quantity_1">
<button role="button">-</button>
<span >Qty:</span>
<input type="number" min="0" size="2" name="updates[]" id="updates_33467117961304" value="1">
<button role="button"> </button>
</div>
CodePudding user response:
Thanks to @Barmar and @Ryan Wilson I achieved by using 'siblings'
$('.qtyplus').on('click', function(e) {
var qty = parseInt( $(this).siblings(".quantity").val() );
})