我需要帮助来解决这个问题。我有一个收集图形的文本框。现在我可以计算该值的10%,然后将结果添加到文本框中的初始值,以获得包含10%的最终值。我需要帮助的是如何在没有提交和表单的情况下在另一个文本框中显示最终值。也就是说,当在第一个文本框中输入值时,会自动计算百分比并将其添加到初始数字中,并在第二个文本框中输出结果。
计算百分比的代码如下:
<?php
$percentage = 10;
$percentindecimal = $percentage / 100;
$amountdue = ($percentindecimal * $amountneeded) + $amountneeded;
?>
<form>
<input name="amountneeded" type="text">
<output name="amountdue" type="text"></output>
</form>
答案 0 :(得分:1)
为了使您的表单能够在未提交的情况下与PHP脚本进行通信,您需要使用JavaScript POST
将value
信息添加到PHP脚本AJAX。虽然 可以使用AJAX,但考虑到您的PHP脚本相当小(并且您无论如何都需要JavaScript),只需在JavaScript本身进行计算就更有意义了(切出PHP完全)。
为此,我建议调用onblur
函数this
keyword,<input>
通过.innerHTML
传递function calculate(input) {
input = parseInt(input); // State that the input received is a number
// Without the parsing, the addition would be *appended* to the input value
input += input / 10; // Add 10% of input to itself
document.getElementsByTagName('span')[0].innerHTML = input; // Output the result
}
。然后,您将在此函数中进行计算,然后使用 .getElementsByTagName
将结果输出到第二个元素。考虑到您没有ID或类,定位所需输出元素的最简单方法是使用 requirements files :
<form>
<input name="amountneeded" type="text" onblur="calculate(this.value)">
<span name="amountdue" type="text"></span>
</form>
&#13;
<output>
&#13;
请注意,<span>
不是有效的HTML元素,因此我已将其替换为{{1}}。
希望这有帮助! :)