Peter Leupold Peter Leupold - 13 days ago 7
PHP Question

Change value of HTML-input field with PHP

With PHP I generate something like this:

<form>
<table>
<tr>
<td>Total:</td>
<td><input type="text" id="total" disabled value="0"> </td>
</tr>
<tr>
<td>Field 1:</td>
<td><input type="text" id="field1" value="1"> </td>
</tr>
<tr>
<td>Field 2:</td>
<td><input type="text" id="field2" value="2"> </td>
</tr>
</table>




Now the first input ("total") should contain the sum of all the "field" inputs. Summing them in a PHP variable is not a problem. But once I am down at the end of the table, can I change the value of "total"?

Workarounds I can think of are


  • placing the total at the end; but then my page would not look the way I desire.

  • do the loop through the data twice, first to do the sum, then to write the HTML. But that looks inefficient.

  • storing the sum in a hidden input and writing it later with javascript.



So, again, can I still change the value of "total" with PHP after having generated the entire table?

Answer

Well, you can still do it in PHP if that's what you need/want to. Just don't echo your data inside the loop, store the output in 2 variables and print it after the loop in the order you need. Something like this

$total = 0; $bodytr = "";

for($i=1;$i<=10;$i++){
    $total += $i;
    $bodytr .= "<tr><td>$i</td></tr>\n";
}

echo "<table>\n";
echo "<tr><td>$total</td></tr>\n";
echo $bodytr;
echo "</table>";
Comments