Skip to content

Instantly share code, notes, and snippets.

@TomasHurtz
Last active June 14, 2021 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomasHurtz/2acb6a4142faeafd390a749df764eb02 to your computer and use it in GitHub Desktop.
Save TomasHurtz/2acb6a4142faeafd390a749df764eb02 to your computer and use it in GitHub Desktop.
"number of persons" form field has dynamic created IDs. The field QTY input type="number"
I've added buttons and some jquery, however, because I have multiple "person_types" fields, the plus / minus onclick is affecting all the fields
How to target the individual fields using something like a foreach - but within the jquery?
current code in functions file
// get IDs from dynamic person_type field
$("input[id^='wc_bookings_field_persons_']").each(function() {
var id = parseInt(this.id.replace("wc_bookings_field_persons_", ""), 10);
var qty = $("#wc_bookings_field_persons_" + id);
// target the form
$('form.cart').on( 'click', 'button.plus, button.minus', function() {
// Get current quantity values
var qty = $( this ).closest( 'form.cart' ).find( "#wc_bookings_field_persons_" + id);
// also tried this
// var qty = $( this ).closest( 'form.cart' ).find( "#wc_bookings_field_persons_" + id + ".qty");
var val = parseFloat(qty.val());
var max = parseFloat(qty.attr( 'max' ));
var min = parseFloat(qty.attr( 'min' ));
var step = parseFloat(qty.attr( 'step' ));
// Change the value if plus or minus
if ( $( this ).is( '.plus' ) ) {
if ( max && ( max <= val ) ) {
qty.val( max );
}
else {
qty.val( val + step );
}
}
else {
if ( min && ( min >= val ) ) {
qty.val( min );
}
else if ( val > 1 ) {
qty.val( val - step );
}
}
});
});
and the html in the numbers.php bookings template file (basically just adding buttons)
<p class="form-field form-field-wide <?php echo esc_attr( implode( ' ', $class ) ); ?>">
<label for="<?php echo esc_attr( $name ); ?>"><?php echo esc_html( $label ); ?>:</label>
<button type="button" class="minus" >-</button>
<input class="qty"
type="number"
value="<?php echo ( ! empty( $min ) ) ? esc_attr( $min ) : 0; ?>"
step="<?php echo ( isset( $step ) ) ? esc_attr( $step ) : ''; ?>"
min="<?php echo ( isset( $min ) ) ? esc_attr( $min ) : ''; ?>"
max="<?php echo ( isset( $max ) ) ? esc_attr( $max ) : ''; ?>"
name="<?php echo esc_attr( $name ); ?>"
id="<?php echo esc_attr( $name ); ?>"
/>
<button type="button" class="plus" >+</button>
<?php echo ( ! empty( $after ) ) ? esc_html( $after ) : ''; ?>
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment