我是 jquery 的新手,有一个药物计算器。计算器中的值可以由用户定义,并且按预期工作。但是,我尝试使用下拉列表(SQL 查询驱动)填充字段作为替代选项。
下拉菜单
<select name="stock_item_used" name="stock_item_used" id="stock_item_used" required>
<option value="" disabled selected>Medication</option>
<?php
//Find medications
$stmt = $conn->prepare("SELECT * from rescue_medication_trans
LEFT JOIN rescue_medications ON rescue_medication_trans.med_profile_id = rescue_medications.medication_id
LEFT JOIN rescue_stock_medication ON rescue_stock_medication.medication = rescue_medication_trans.med_profile_id
WHERE rescue_medication_trans.centre_id = :centre_id
ORDER BY common_name ASC");
$stmt->bindParam(':centre_id', $centre_id, PDO::PARAM_INT);
// initialise an array for the results
$instock = array();
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$med_profile_id = $row["med_profile_id"];
$batch_number = $row["batch_number"];
$expiry = $row["expiry"];
$med_common_name = $row["common_name"];
$mcd = $row["concentration_dose"];
$mcv = $row["concentration_volume"];
$dose_type = $row["concentration_dose_type"];
$volume_type = $row["concentration_volume_type"];
//format the exp date
$exp = new DateTime($expiry);
$exp = $exp->format('d-m-Y');
print '<option value="' . $med_profile_id . '" data-dose="' . $mcd . '" data-volume="' . $mcv . '">' . $med_common_name . ' - ' . $mcd . '<i>' . $dose_type . '</i> in ' . $mcv . '<i>' . $volume_type. '</i> (' . $batch_number . ' exp: ' . $exp . ') </option>'; } ?> </select>
jquery 脚本
<script>
var req_dose = 0;
var med_dose = 0;
var med_vol = 0;
var weight = 0;
$("#required_dose").change( function(){
req_dose = $("#required_dose").val();
calcTotals();
});
$("#medication_dose").change( function() {
med_dose = $("#medication_dose").val();
calcTotals();
});
$("#medication_volume").change( function() {
med_vol = $("#medication_volume").val();
calcTotals();
});
$("#animal_weight").change( function() {
weight = $("#animal_weight").val();
calcByweight();
});
var selectdose = document.getElementById("stock_item_used");
selectdose.addEventListener("change", function() {
var optiondose = selectdose.options[selectdose.selectedIndex].getAttribute("data-dose");
document.getElementById('medication_dose').value = optiondose;
calcTotals();
calcByweight();
});
var selectvol = document.getElementById("stock_item_used");
selectvol.addEventListener("change", function() {
var optionvol = selectvol.options[selectvol.selectedIndex].getAttribute("data-volume");
document.getElementById('medication_volume').value = optionvol;
calcTotals();
calcByweight();
});
function calcTotals(){
$("#volume").text(req_dose * (med_vol / med_dose));
}
function calcByweight(){
$("#perweight").text((req_dose * (med_vol / med_dose)) * weight);
}
</script>
行为
表格填充后,我在填充后添加了 calctotals() 以查看它是否会计算表格,但是我一直得到 NaN 或 Infinity。
如果我编辑表单字段,计算器将再次工作,但这违背了从下拉列表中填充的意义。
您需要更新变量,以便计算器采用其实际预期值而不是原始的 0。
NaN
因为您的计算器除以 0,所以得到了结果。我还添加了动物体重和所需剂量的默认值以及 HTML: