首页 > 解决方案 > PHP表单在提交之前检查PHP x + y > z

问题描述

我有以下变量:

$aantalcompleet
$ready
$totaalaantal

$aantalcompleet是从 DB 获取的值。

$totaalaantal也是从 DB 获得的值。

$ready是从表单中获取的值。

我想在提交表单之前检查 $aantalcompleet + $ready > $totaalaantal。

如果此总和为 TRUE,我希望收到一条带有“继续或取消”的确认消息。如果总和为 FALSE,则表单可以在没有消息的情况下进行汇总。

我的表格:

<form action="" method="POST">
<div class="col-lg-3">
  <div class="input-group">
    <span class="input-group-btn">
      <button class="btn btn-default" type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();"><i class="fa fa-trash-o"></i></button>
    </span>
      <input type="number" class="form-control" name="complete" id="complete" value="" placeholder="0">
      <input type="hidden" name="machine" value="<?php echo $machine;?>">
      <input type="hidden" name="base" value="<?php echo $base;?>">
      <input type="hidden" name="lot" value="<?php echo $lot;?>">
      <input type="hidden" name="split" value="<?php echo $split;?>">
      <input type="hidden" name="sub" value="<?php echo $sub;?>">
      <input type="hidden" name="seq" value="<?php echo $seq;?>">
  </div>
</div>
  <button class="btn btn-default" style="height:35px;width:200px" type="submit" value="gereed" name="gereed">Gereed</button>

标签: javascriptphphtmlformsform-submit

解决方案


将此添加到您的页面中的某处<head>

<script>
function onsubmit(event){
    if($aantalcompleet + $ready > $totaalaantal){
        if(!confirm('Continue or Cancel')){
            event.preventDefault();
            return false;
        }
        return true;
    }
    return true;
}
</script>

假设您的 PHP 变量$aantalcompleet,$totaalaantal$ready与您的表单在同一个文件中可用,请将以下代码放置在这些变量具有其预期值的位置(即它们填充有数据库中的值,可能就在您的 sql 查询之后(如果有) )

<script>
    var $aantalcompleet = <?php echo $aantalcompleet; ?>;
    var $totaalaantal = <?php echo $totaalaantal; ?>;  
    var $ready = <?php echo $ready; ?>;
</script>

然后添加onsubmit="return onsubmit(event)"到您的表单标签中,例如

<form action="" method="POST" onsubmit="return onsubmit(event)">


推荐阅读