Search code examples
javascriptphpproductwebshop

Showing price on click input type="radio"?


[Product listing with clickable inputs][1] i'm building a webshop system, and i would like to see on the product page that if a user selects a product size, the price will be displayed of the selected size..

Only the last displayed input works when i click on it.

Product listing with size inputs: https://i.sstatic.net/Wo6Oq.png

    <?php
    $count = 0;
    foreach($original_array as $order_list){
        $count++;
        if($order_list['aantal'] == 0 || $order_list['aantal'] == ''){
            $disableValue = 'disable';
        }
        if($count == 2){
            $checked = 'checked=""';
        }
        ?>
        <div class="sc-item">
            <input type="radio" name="variatie_maat[]" value="<?=$order_list['maat'];?>" onclick="myFunction();" id="<?=$order_list['maat'];?>-maat" <?=$disableValue;?> <?=$checked;?>>
            <label for="<?=$order_list['maat'];?>-maat"><?=$order_list['maat'];?></label>
            <input style="display:none;" value="<?=$order_list['prijs'];?>" id="prijs-<?=$order_list['prijs'];?>" name="variatie_prijs[]">
        </div>
        <?php

        }
    ?>
<script>
// Here the value is stored in new variable x  
      function myFunction() { 
          var x =  
              document.getElementById("prijs-<?=$order_list['prijs'];?>").value; 

          document.getElementById( 
            "price").innerHTML = x; 
      } 

</script>
'''


Solution

  • Try this.

    <?php
    $count = 0;
    foreach($original_array as $order_list){
        $count++;
        if($order_list['aantal'] == 0 || $order_list['aantal'] == ''){
            $disableValue = 'disable';
        }
        if($count == 2){
            $checked = 'checked=""';
        }
        ?>
        <div class="sc-item">
            <input type="radio" name="variatie_maat[]" value="<?=$order_list['maat'];?>" onclick="myFunction('<?=$order_list['prijs'];?>');" id="<?=$order_list['maat'];?>-maat" <?=$disableValue;?> <?=$checked;?>>
            <label for="<?=$order_list['maat'];?>-maat"><?=$order_list['maat'];?></label>
            <input style="display:none;" value="<?=$order_list['prijs'];?>" id="prijs-<?=$order_list['prijs'];?>" name="variatie_prijs[]">
        </div>
        <?php
    
        }
    ?>
    
    <script>
    function myFunction(id) {
      var x = document.getElementById("prijs-" + id).value;
      document.getElementById("price").innerHTML = x;
    }
    </script>