The original code is using prevAll
on the minus button, but the target input appears later in the DOM. PrevAll
worked fine for the plus button though, since the targeted input comes before the plus button.
The modified code below is tested and working:
jQuery(document).ready(function ($) {
// Containing selector
var parentSelector = $('.quantity');
// If it's on the page
if( parentSelector.length ) {
// Get the original HTML
var numberInputs = parentSelector.html();
// Minus button
var btnLess="<button class="minus">-</button>";
// Change number to text
var textInputs = numberInputs.replace('type="number"', 'type="text"');
// Plus button
var btnMore="<button class="plus">+</button>";
// Append it all
parentSelector.append(btnLess + textInputs + btnMore);
// Hide the original
parentSelector.find('input[type="number"]').hide();
// increase or decrease the count
$('.plus, .minus').on('click', function(e) {
e.preventDefault();
if( $(e.target).hasClass('plus') ) {
var newCounter = $(this).prevAll('input.qty[type="text"]');
var oldCounter = $(this).prevAll('input.qty[type="number"]');
var counterVal = newCounter.val();
counterVal++ ;
} else {
var newCounter = $(this).nextAll('input.qty[type="text"]');
var oldCounter = $(this).nextAll('input.qty[type="number"]');
var counterVal = newCounter.val();
counterVal-- ;
}
// Apply to both inputs
newCounter.val(counterVal);
oldCounter.val(counterVal);
});
}
});