我想从html中的不同选择中计算2个选项,并在输入字段中显示结果。第一个select将从mysql数据库填充,第二个select将填充第一个数据库的1个选项。我想将它们相乘,并在最后一个输入字段中显示结果。举个例子:
数据库的表字段是“id product”-id数量价格类型表视图
下面是我想要的结果:显示
当用户选择数量时,相应的值将显示到下一个字段。
在最后一个输入字段中,我要计算前面的选择
用户只能选择数量,不能选择价格
我用php做了一个select并做了一个数组,这个数组被转换成javascript数组对象
<?php
$sth = $conn->prepare("SELECT quantity,price FROM eb_products_price WHERE product_id = 20");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$json_array = json_encode($result);
print_r($result);
有了这段代码,我唯一能做的就是用foreach显示数量,但是价格仍然是最后一个,并且在我更改数量时它不会改变。
我找到了一种显示正确价格的方法,但是使用javascript,这里是代码
<script>
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity= document.getElementById("quantity");
var price= document.getElementById("price");
var arrprice = quantity.options[quantity.selectedIndex].value;
while (price.options.length) {
price.remove(0);
}
var prices = arrayObjects[arrprice];
if (prices) {
var i;
for (i = 0; i < prices.length; i++) {
var price1 = new Option(prices[i], i);
price.options.add(price1);
}
}
}
</script>
下面是不使用最后一部分代码的计算函数:
calculate = function()
{
var quantity= document.getElementById('quantity').value;
var price= document.getElementById('price').value;
var number = parseFloat(quantity)*parseFloat(price);
var n = number.toFixed(2);
document.getElementById('result').value = n
}
2条答案
按热度按时间jhkqcmku1#
要动态更改html元素,需要事件侦听器,如下面的onchange示例:
atmip9wb2#
在javascript中,要获取select的选定元素(值),请使用: