按下按钮调用php函数


calling a php function by press the button

我用php写了下面的代码。在这个代码中,我想计算水费

但当我按下按钮时,结果不会显示proplem在哪里。知道我想使用用户输入的值。

<!DOCTYPE html>
<html>
<body>
<form>
القيمة: <input type="text" name="cal"><br>
<button onclick="myFunction("cal")">إحسب التكلفة</button>
</form>
<script>
function myFunction($x) {
$x=$x%1000;
if($x<=15){
$x=$x*0.10;
 return $x;}
elseif($x>=16&&$x<=30){
$x=$x*1.00;
 return $x;}
elseif($x>=31&&$x<=45){
$x=$x*3.00;
 return $x;}
elseif($x>=46&&$x<=60){
$x=$x*4.00;
 return $x;}
else{
$x=$x*6.00;
 return $x;}
}
</script>
</body>
</html>

实现这一点的另一种方法是将onClick事件添加到按钮和调用函数中。

示例。

// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

首先,javascript中没有elseif运算符。您应该使用else if。此外,您还需要从输入中获取值,并将其传递给myFunction。我修改了你的样品,检查这个plunker

请尝试以下脚本。问题是您使用elseif,而不是如果,否则如果而且你调用的函数是错误的。我在输入字段中添加了一个id。请检查

    <!DOCTYPE html>
    <html>
    <body>
    <form>
        <input type="text" name="cal" id="cal"><br>
        <button type=button onclick="document.getElementById('data').innerHTML = myFunction(document.getElementById('cal').value)">إحسب التكلفة</button>
<hr>
Result:<span id="data"></span>
    </form>
    <script>
        function myFunction($x) {
            $x = $x % 1000;
            if ($x <= 15) {
                $x = $x * 0.10;
                return $x;
            }
            else if ($x >= 16 && $x <= 30) {
                $x = $x * 1.00;
                return $x;
            }
            else if ($x >= 31 && $x <= 45) {
                $x = $x * 3.00;
                return $x;
            }
            else if ($x >= 46 && $x <= 60) {
                $x = $x * 4.00;
                return $x;
            }
            else {
                $x = $x * 6.00;
                return $x;
            }
        }
    </script>