簡體   English   中英

使用javascript從2個選擇字段計算到輸入字段的數據

[英]Calculate data to an input field from 2 select fields with javascript

我想從HTML中的不同選擇計算2個選項,並將結果顯示在輸入字段中。 第一個選擇將從mysql數據庫填充,第二個選擇將填充1個選項,即第一個選項。 我想將它們相乘並在最后一個輸入字段中顯示結果。 這是一個例子:

數據庫的表字段是“ id產品” -id數量價格類型表視圖

這是我想要的結果: 顯示

當用戶選擇數量時,相應的值將顯示在下一個字段中。

之后,在最后一個輸入字段中,我想計算先前的選擇

  • 用戶只能選擇數量而不是價格

我用php進行了選擇,並制作了一個數組,該數組被轉換為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
   }

要動態更改HTML元素,您需要以下事件監聽器,如onChange示例:

 var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]} function products() { var quantity = document.getElementById("quantity"); var factor = document.getElementById("factor"); // added var price= document.getElementById("price"); // Fill dropdown (quantity) while (quantity.options.length) { quantity.remove(0); } // fill by key for( var quantity_key in arrayObjects ) { var quantity_option = new Option( quantity_key, quantity_key ); quantity.options.add(quantity_option); } // onChange-Listener quantity.onchange = () => { factor.value = arrayObjects[quantity.value]; // look for factor by key in arrayObjects price.value = Math.round( quantity.value *arrayObjects[quantity.value] ); }; } products(); 
 <select id='quantity'></select> KG <input type='text' id='factor' readonly="readonly"> <input type='text' id='price' readonly="readonly"> 

在javascript中,要獲取select的選定元素(值),請使用:

var e = document.getElementById("quantity");
var quantity= e.options[e.selectedIndex].text;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM