我有一个单选按钮列表和一个从数据库填充的下拉列表:
<ul id="radio" class="input-list">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '<li>
<input class="selectedoptions" id="'.$case_id.'" name="config-prod" value="'.$case_price.'" type="radio">
<label class="sub-label" for="'.$case_id.'">'.$case_name.' [£'.$case_price.']</label>
</li>';
}
$stmt->close();
?>
</ul>
<?php
echo "<select class='form-control' id='plist' name='partlist'>";
$type = "processors";
$stmt2 = mysqli_prepare($link, "SELECT id, name, price FROM parts WHERE type=?");
$stmt2->bind_param("s", $type);
$stmt2->execute();
$stmt2->bind_result($cpu_id, $cpu_name, $cpu_price);
while($stmt2->fetch()){
echo "<option value='$cpu_price'>$cpu_name</option>";
}
$stmt2->close();
echo "</select>";
?>
我希望能够从两个列表中获得所选商品的价格。我试图用JS做到这一点:
<script>
var buildcost = 25.00;
function updateTotal() {
var radios = document.getElementsByName('config-prod');
var partcost;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
partcost = parseInt(radios[i].value);
break;
}
}
total_cost = buildcost + partcost;
document.getElementById('total').innerHTML = total_cost;
}
</script>
total_cost应该输出到此:
<input name="buildTotal" id="total" type="text" class="transparentFieldy float-price" disabled="" />
但是,这不会输出任何内容。如何更改此设置,以便能够根据所选元素计算价格?谢谢!
答案 0 :(得分:1)
要设置输入元素的内容,必须使用value
属性而不是innerHTML
。如果您要使用货币,还应该考虑使用parseFloat
。
let buildcost = 25.00;
function updateTotal() {
let radios = document.getElementsByName('config-prod');
let select = document.getElementById('plist');
let partcost = 0;
for (let i = 0, j = radios.length; i < j; i++) {
if (radios[i].checked) {
partcost = parseFloat(radios[i].value);
break;
}
}
partcost += parseFloat(select.options[select.selectedIndex].value);
let total_cost = buildcost + partcost;
document.getElementById('total').value = total_cost.toFixed(2);
}
<ul id="radio" class="input-list">
<li>
<input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
<label for="item-1">Item 1 [£1.00]</label>
</li>
<li>
<input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
<label for="item-2">Item 2 [£12.34]</label>
</li>
<li>
<input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
<label for="item-3">Item 3 [£9.99]</label>
</li>
</ul>
<select id="plist" name="partlist" onchange="updateTotal();">
<option value="99.99">CPU 1</option>
<option value="123.00">CPU 2</option>
<option value="250.54">CPU 3</option>
</select>
<br>
Total: <input id="total" type="text"><button id="update" onclick="updateTotal();">Update</button>