Javascript 根据Select的选择动态更改变量的值
我有下面的PHP代码,在这里我打印我的HTML,我有一个变量$price和另一个$numoffJavascript 根据Select的选择动态更改变量的值,javascript,php,select,drop-down-menu,Javascript,Php,Select,Drop Down Menu,我有下面的PHP代码,在这里我打印我的HTML,我有一个变量$price和另一个$numoff <?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 <= $numofguest
<?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
所以默认情况下,guest的num是1,总价=5美元
但是如果用户选择num of guest=2,我希望总价改为10美元,如果num of guest=3,我希望总价改为15美元
非常感谢使用select的onChange事件运行javascript函数,更改打印总价的HTML。更具体地说,我需要查看打印总价的HTML代码。您的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);
});
要从更改时的“选择”下拉列表中获取值,请将该值放入范围中
演示:因此,您需要使用Javascript更新客户端中的价格标签。您可以创建一个简单的函数来计算并显示价格 通过将onchange属性添加到选择列表中,可以让函数在选择列表更改时执行 大概是这样的:
<?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>
试试这个
<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>