Change innerHTML if quantity is selected

Viewed 50

I have written the following code that changes an output (innerHTML) when the quanitity changes.

add_action( 'woocommerce_before_add_to_cart_quantity', 'qty_output_text' );
 
function qty_output_text() {
   global $product;
    if ( $product->is_type('variable') && is_product() ) {
    ?>
    <script>
    jQuery(document).ready(function($) {
            var quantita_iniziale = $('[name=quantity]').val();
         $( '[name=quantity]' ).change( function(){
             var quantita_iniziale = $('[name=quantity]').val();
             document.getElementById("test123").innerHTML= quantita_iniziale+"K = "+quantita_iniziale+" test";
        });

    </script>
    <?php
   }
}

If I then change the quantity in the product, then the output is correct.

The product has 2 variations. If I select variation 1, the minimum quantity is set to 15. However, my script does not recognize this change and therefore does not output the correct number. Do you know what I can do here? The minimum number should also change [name=quantity] or not?

EDIT: Here is a video of my problem https://www.veed.io/view/e70ba12f-84e4-4a21-8966-bb1f332077ce

1 Answers

I think you need to get the value of the element you just changed.

You can do that by using this. If you want to display both quantities in your div then you need to query both elements separately and get each of their values.

var quantita_iniziale = $('[name=quantity]').val();
$('[name=quantity]').change(function() {
  var quantita_iniziale = $(this).val();
  document.getElementById("test123").innerHTML = quantita_iniziale + "K = " + quantita_iniziale + " test";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="quantity">
  <option> Change me </option>
  <option value="1">1 </option>
  <option value="2">2 </option>
</select>

<select name="quantity">
<option> Change me </option>
  <option value="1">1 </option>
  <option value="2">2 </option>
</select>
<p id="test123">

</p>

Related