With the following code on our website (build with WordPress and WooCommerce) located in the file /woocommerce/templates/global/quantity-input.php
, I added some code in order to have several “Increment Value” buttons. Each button is supposed to increase the quantity value by 1 of the field located next to it.
The trouble is that all buttons increases only the first top field value.
I would like that each button interact only with the field located next to it, without reflecting on other fields.
What i am doing wrong?
Please help me.
echo "<script>
var i = 0;
function buttonClick() {
document.getElementById('inc').value = ++i;
</script>";
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
?>
<div class="quantity">
<form>
<input type="number" id="inc" onfocus="if(this.value == '0') { this.value = ''; }" step="<?php echo esc_attr( $step ); ?>" min="<?php echo esc_attr( $min_value ); ?>" max="<?php echo esc_attr( $max_value ); ?>" name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( $input_value ); ?>" title="<?php echo esc_attr_x( 'Qty', 'Product quantity input tooltip', 'woocommerce' ) ?>" class="input-text qty text" size="4" />
<input type="button" onclick="buttonClick()" value="Increment Value" />
</form>
</div>
When document.getElementById(‘inc’) is called, it gets the first input with id “inc”. So it updates that input field. You need a unique id for the input fields or find another way to find the correct input field to update.
You need something like this, pass id of the input while calling function and increment the value of that input whose id is passed in function…
This is working, Try it….