【问题标题】:PHP Form check if PHP x + y > z before submitPHP表单在提交之前检查PHP x + y > z
【发布时间】:2019-07-26 16:51:09
【问题描述】:

我有以下变量:

$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>

【问题讨论】:

  • 您好!您是否有任何代码可以显示您是如何尝试此解决方案的?
  • 在表单提交之前执行 ajax(如果您的计算取决于服务器)或签入 javascript。
  • 最好使用Javascript而不是PHP
  • 在表单提交前使用ajax进行检查。
  • @SomnathMondal 这里没有理由使用 Ajax。检查可以很容易地在客户端 JS 中完成,因此用户可以在数据发送到服务器之前立即获得有关表单是否有效的反馈。 (当然你还需要在服务器端进行验证。)

标签: javascript php html forms form-submit


【解决方案1】:

将此添加到您的页面&lt;head&gt;中的某处

<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)"添加到您的表单标签中,例如

&lt;form action="" method="POST" onsubmit="return onsubmit(event)"&gt;

【讨论】:

  • 表单仍在提交,没有确认消息
  • @RicoKrouweel 你能打开浏览器开发工具控制台并检查 $aantalcompleet、$totaalaantal、$ready JavaScript 变量的值吗?他们还好吗?控制台有什么错误吗?
  • 错误:在 HTMLFormElement.onsubmit 处超出最大调用堆栈大小
  • @RicoKrouweel 我已经根据一些假设更新了答案。你能检查一下再试一次吗?
  • 还是和以前一样
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 2016-02-04
  • 2011-12-04
相关资源
最近更新 更多