简体   繁体   中英

PHP using mysql need to calculate the total cost of all dropdown boxes

So I have multiple dropdown boxes and they have a price inside the drop down box and I want to gather all the prices of each dropdown box and echo it as a total price. So far I have managed to echo the price but it's only displaying the last product of each dropdown box so it doesn't change price when the user selects different products.

        <?php
      //PSU QUERY
  $sqlpsu="SELECT id, psu, price, psuWATT FROM  PSU";
  $result = mysql_query($sqlpsu);

    echo "<select name='psu'>";
    while ($row = mysql_fetch_array($result)) {

        echo '<option value="'.$row["id"].'">'.$row["psu"]. " £" .$row["price"].'</option>';
        $pricePsu = $row["price"];
    }
    echo "</select>";
    ?>

before while set

$pricePsu = 0;

in the while use

$pricePsu += $row["price"];

After while echo "$pricePsu"

Option html

<select name="psu" id="psu" multiple="multiple">
  <option value="1" price="5">option1 $5</option>
  <option value="2" price="10">option2 $10</option>
  <option value="3" price="15">option3 $15</option>
</select>
<div></div>

Option javascript

$( "select" )
  .change(function() {
    var total = 0;
    var str = "";
    $( "#psu option:selected" ).each(function() {
      total += parseInt($( this ).attr("price")) ;
    });
    $( "div" ).text( total );
  })
  .trigger( "change" );

Example! https://jsfiddle.net/Cuchu/epxvhfyh/

Good practice:

echo "<option value='{$row['id']}' price='{$row['price']}'>{$row['psu']} £ {$row['price']}</option>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM