繁体   English   中英

根据选择的选择即时更改变量的值

[英]Change the value of a variable on the fly depending on the selection of a Select

我有以下PHP代码可在其中打印HTML,并且有一个变量$ price和另一个$ numofguests

<?php
echo '$' . $price ;

$i = 1;
//This print values of number of guest for example: 1,2,3,4
echo 'Select Number of Guests';
echo '<select name="numberofguests">';
while ($i <= $numofguests):
        echo $i;
    echo '<option value="' .$i. '">' .$i. '</option>'; 
        $i++;
endwhile;
echo '</select>'; 
?>

如何根据用户选择即时打印出总价?

示例:假设$ price = $ 5,并且来宾选项的数量为:1,2,3

因此,默认情况下,来宾人数为1,总价格= $ 5

但是,如果用户选择num = 2,我希望总价格更改为$ 10,如果num = 3,则希望总价格更改为$ 15

非常感谢你

试试这个。

 <div id="pricediv"></div>
    <?php
    $numofguests = 5;
    $i = 1;
    echo 'Select Number of Guests'."</br>";
    echo '<select name="numberofguests" onchange="total(this.value)">';
    while ($i <= $numofguests):
            echo $i;
        echo '<option value="' .$i. '">' .$i. '</option>'; 
            $i++;
    endwhile;
    echo '</select>'; 
    ?>

    <script>
    function total(guest){
    var price = guest*5;
    document.getElementById("pricediv").innerHTML="Price for "+guest+" guests is $"+price; 
    }

    </script>

您的php代码如下:

# index.php
<?php
$i = 1;
?>
<select id="room-selector" name="numberofguests">
  <?php while ($i <= $numofguests): ?>
    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
    <?php $i++; ?>
  <?php endwhile; ?>
</select>
<p>No. of guest selected : <span id="guest-count"></span></p>

现在在javascript中:

$("#room-selector").change(function() {
  var price = 5; // or var price = <?php echo $price; ?>;
  $('#guest-count').text($(this).val() * price);
});

使其在更改时从选择下拉列表中获取值并将其放入跨度中。

演示: JSBin

因此,您将要使用Javascript更新客户端中的价格标签。 您可以创建一个简单的函数来计算价格并显示它。

通过将onchange属性添加到您的<select>您可以使函数在选择列表更改时执行。

像这样:

<?PHP
   $price = 10;
   $numofguests = 5;

   $options="";

   while ($i <= $numofguests):
       $options .= '<option value="' .$i. '">' .$i. '</option>'; 
       $i++;
   endwhile;
?>

<html>
    <p id="price"><?= $price; ?></p>

    <select name="numberofguests" id="numberofguests" onchange="updatePrice()">
        <?= $options; ?>
    </select>

    <script>
        function updatePrice(){
            // set the value of the JS price with the value from PHP
            var price = <?= $price; ?>;
            var qty = document.getElementById("numberofguests").value;
            var totalPrice = price * qty;

            var destination = document.getElementById("price");

            destination.innerHTML = totalPrice;
        }
    </script>

</html>

使用select的onChange事件运行一个javascript函数,该函数可更改您在打印总价的HTML。 更具体地说,我将需要在打印总价的地方看到HTML代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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