Using JS and WP custom field to set Input Step Increment – not working

I have a custom field in the WP admin for the site manager to select a quantity step of products sold at once. So if would like products sold in pairs, or 3’s etc.

I have some code borrowed from the Woocommerce qty plugin, but I can’t get it working right with the custom field value:

<?php if( get_field(‘ticket_step_choose’) ) { ?>
<h3><?php the_field(‘ticket_group_step’); ?></h3>
<script>
// Quantity Input plus/minus btns
jQuery(‘.quantity’).on(‘click’, ‘.qty-increase’, function(e) {
var $input = jQuery(this).closest(‘.quantity’).find(‘input.qty’);
var $val = parseInt($input.val());
$input.val( $val + <?php echo the_field(‘ticket_group_step’); ?> ).change();
});

jQuery(‘.quantity’).on(‘click’, ‘.qty-decrease’, function(e) {
var $input = jQuery(this).closest(‘.quantity’).find(‘input.qty’);
var $val = parseInt($input.val());
var $min = jQuery($input).attr(‘min’);
$min = ( $min == 0 ) ? 0 : $min; console.log($min);
if( $val > $min){
$input.val( $val – <?php echo the_field(‘ticket_group_step’); ?> ).change();
}
});
</script>
<?php } else { ?>
<script>
// Quantity Input plus/minus btns
jQuery(‘.quantity’).on(‘click’, ‘.qty-increase’, function(e) {
var $input = jQuery(this).closest(‘.quantity’).find(‘input.qty’);
var $val = parseInt($input.val());
$input.val( $val + 1 ).change();
});

jQuery(‘.quantity’).on(‘click’, ‘.qty-decrease’, function(e) {
var $input = jQuery(this).closest(‘.quantity’).find(‘input.qty’);
var $val = parseInt($input.val());
var $min = jQuery($input).attr(‘min’);
$min = ( $min == 0 ) ? 0 : $min; console.log($min);
if( $val > $min){
$input.val( $val – 1 ).change();
}
});
</script>

Here, I’m trying to set that if a custom step value is present, use that, otherwise increments of 1 is the default.

I can get the script working from a functional perspective on the form, but if I set the step value to 2 (the_field(‘ticket_group_step’)), the first qty added is 3 and goes up in increments of 3 – not 2. It’s like it’s taking the step value and adding it to 1 every time.

Writing custom JS isn’t my strongest, but I’ve reached a point where I don’t know how to correct this last part.

I’d also like the input to not go below 0 if possible, currently allowing -1 etc.

Any help / advice would be appreciated.

Read more here:: Using JS and WP custom field to set Input Step Increment – not working

Leave a Reply

Your email address will not be published. Required fields are marked *