Получить сумму нескольких выпадающих:
<html>
<head>
<script type="text/javascript">
function sum_all()
{ var fru = document.getElementById("fruits");
var che = document.getElementById("cheeses");
var sum = parseInt(fru.options[ fru.selectedIndex ].title) +
parseInt(che.options[ che.selectedIndex ].title);
document.getElementById("total").innerHTML = sum;
}
</script>
</head>
<body>
<select id="fruits" onchange="sum_all()">
<option value="1" title="1">Banana</option>
<option value="2" title="2">Apple</option>
<option value="3" title="5">Melon</option>
</select>
<select id="cheeses" onchange="sum_all()">
<option value="1" title="12">Cheddar</option>
<option value="2" title="6">Fresh</option>
<option value="3" title="15">Mozarella</option>
</select>
<br/>
Total: <span id="total"></span>
</body>
</html>
Everytime вы выбираете один выпадающий список, это покажет сумму цен. «Title» - это цены на продукцию.
Теперь давайте исправим код:
<div id="content">
<?php
$link = mysql_connect('root', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$selected = mysql_select_db("database",$link)
or die("Could not select examples");
?>
<table border="1" style="width:auto;">
<tr>
<td>
<form action="checkout.php" method="POST">
<label for="intel" INTEL Build:</label>
<?php
//MOTHERBOARD QUERY
$sql="SELECT id, mobo, price FROM MOBO WHERE mobo LIKE 'INTEL%' ";
$result = mysql_query($sql);
//print '<form action="checkout.php" method="post">';
print "<select name='mobo'>";
while ($row = mysql_fetch_array($result)) {
print '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["mobo"]. " £" .$row["price"].'</option>';
}
print "</select>";
?>
</td>
</tr>
<tr>
<td>
<?php
//CPU QUERY
$sqlcpu="SELECT id, cpu, price FROM CPU WHERE cpu LIKE 'INTEL%' ";
$result = mysql_query($sqlcpu);
print "<select name='cpu'>";
while ($row = mysql_fetch_array($result)) {
print '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["cpu"]. " £" .$row["price"].'</option>';
}
print "</select>";
?>
</td>
</tr>
<tr>
<td>
<?php
//RAM QUERY
$sqlram="SELECT id, ram, price FROM RAM ";
$result = mysql_query($sqlram);
echo "<select name='ram'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["ram"]. " £" .$row["price"].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>
<?php
//HARDDRIVE QUERY
$sqlharddrive="SELECT id, harddrive, price FROM HARDDRIVE";
$result = mysql_query($sqlharddrive);
echo "<select name='harddrive'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["harddrive"]. " £" .$row["price"].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>
<?php
//GPU QUERY
$sqlgpu="SELECT id, gpu, price, gpuWATT FROM GPU";
$result = mysql_query($sqlgpu);
?>
<select id ="gpu" onChange="sum_all()">
<?php
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["gpu"]. " £" .$row["price"].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>
<?php
//PSU QUERY
$sqlpsu="SELECT id, psu, price, psuWATT FROM PSU";
$result = mysql_query($sqlpsu);
?>
<select id ="psu" onChange="sum_all()">
<?php
$pricePsu = 0;
while ($rows = mysql_fetch_array($result)) {
echo '<option value="'.$rows["id"].'" title="'.$row["price"].'">'.$rows["psu"]. " £" .$rows["price"].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>
<?php
//COMPUTERCASE QUERY
$sqlcomputercase="SELECT id, computercase, price FROM COMPUTERCASE";
$result = mysql_query($sqlcomputercase);
echo "<select name='computercase'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'" title="'.$row["price"].'">'.$row["computercase"]. " £" .$row["price"].'</option>';
}
echo "</select>";
?>
</td>
</tr>
</table>
<script type="text/javascript">
function sum_all()
{ var mobo = document.getElementById("mobo");
var cpu = document.getElementById("cpu");
var ram = document.getElementById("ram");
var harddrive = document.getElementById("harddrive");
var gpu = document.getElementById("gpu");
var sum = parseInt(mobo.options[ mobo.selectedIndex ].title) +
parseInt(cpu.options[ cpu.selectedIndex ].title) +
parseInt(ram.options[ ram.selectedIndex ].title) +
parseInt(harddrive.options[ harddrive.selectedIndex ].title) +
parseInt(gpu.options[ gpu.selectedIndex ].title);
document.getElementById("total").innerHTML = sum;
}
</script>
<?php
//echo "Total Cost: £".$grandtotal = $priceMobo + $priceCpu + $priceRam + $priceHARDDRIVE + $priceGpu + $pricePsu + $priceComputercase;
$_SESSION['checkoutTotal'] = $grandtotal;
echo '<br></br>';
?>
<br/>
Total: <span id="total"></span>
Я добавил «заголовок» для всех выбирает и создали несколько переменных в JavaScript функции ... и просто добавил <span>
на дне!
Теперь давайте храним данные в форме. Javascript функция будет хранить идентификаторы выбранных элементов в виде полей, а затем отправляет форму, кстати, форма невидима, потому что мы не хотим, чтобы пользователь редактировать его:
<script type="text/javascript">
function sum_all()
{ var mobo = document.getElementById("mobo");
var cpu = document.getElementById("cpu");
var ram = document.getElementById("ram");
var harddrive = document.getElementById("harddrive");
var gpu = document.getElementById("gpu");
var sum = parseInt(mobo.options[ mobo.selectedIndex ].title) +
parseInt(cpu.options[ cpu.selectedIndex ].title) +
parseInt(ram.options[ ram.selectedIndex ].title) +
parseInt(harddrive.options[ harddrive.selectedIndex ].title) +
parseInt(gpu.options[ gpu.selectedIndex ].title);
document.getElementById("total").innerHTML = sum;
// STORE THE "ID"S IN THE FORM FIELDS.
document.getElementById("frm_mobo").value = mobo.options[ mobo.selectedIndex ].value;
document.getElementById("frm_cpu").value = cpu.options[ cpu.selectedIndex ].value;
document.getElementById("frm_ram").value = ram.options[ ram.selectedIndex ].value;
document.getElementById("frm_hd").value = harddrive.options[ harddrive.selectedIndex ].value;
document.getElementById("frm_gpu").value = gpu.options[ gpu.selectedIndex ].value;
document.getElementById("frm").submit(); // SUBMIT FORM.
}
</script>
<form id="frm" method="post" action="anyname.php" style="display:none;">
<input type="text" id="frm_mobo" name="frm_mobo"/>
<input type="text" id="frm_cpu" name="frm_cpu"/>
<input type="text" id="frm_ram" name="frm_ram"/>
<input type="text" id="frm_hd" name="frm_hd"/>
<input type="text" id="frm_gpu" name="frm_gpu"/>
</form>
Вы будете необходимо создать файл «anyname.php» (вы выбираете лучшее имя), чтобы получить данные от $_POST[ "frm_mobo" ]
, $_POST[ "frm_cpu" ]
и т. д. и сделать с ними что-то.
ну, да. вы продолжаете сбросить $ priceGpu на каждой итерации цикла. поэтому вы получите последнее значение, которое вы получили из db. как/где вы хотите повторить эту цену? вам нужно что-то вроде 'if ($ row ['id'] == $ user_selected_gpu) {$ price = ...}', чтобы получить только цену за фактический выбранный пользователем gpu. –
Я просто хочу отразить цену в раскрывающемся списке, так что, как и общая стоимость – bill186
mysql_ * функции устарели от PHP 5.5, вместо этого используют mysqli_ * функции. См. [Этот вопрос] (http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) для получения дополнительной информации – ethane