【问题标题】:Can I get the name of submit button in another form?我可以以其他形式获取提交按钮的名称吗?
【发布时间】:2011-07-30 04:30:27
【问题描述】:

我有一个包含 3 个提交按钮的表单。它们的名称是在循环中生成和分配的。现在如果我使用 post 方法,如何访问被点击的提交按钮的名称。

以下是我的代码示例:

**one.php**

    <form name="one" method="post" action="two.php">

    <?php
    while($i=1;$i<=3;$i=$+1)
    {
    ?>
    <button type="submit" name="<?php echo $i ?>" value="<?php echo $i ?>" >
    </button>
    <?php
    }
    ?>

    </form>

**two.php**

    {
    code???????
    }

也许我可以在 one.php 中为按钮标签使用 onsubmit 属性,但我无法获得输出。有什么建议吗?

【问题讨论】:

    标签: php html forms button submit


    【解决方案1】:

    生成另一个输入元素

    <input type="hidden" name="buttonId" value="<?php echo $i ?>" />
    

    然后用$_REQUEST['buttonId']获取你的ID

    【讨论】:

      【解决方案2】:

      如果有一个条目包含您的三个按钮中的每一个的名称,您只需检查$_POST

      for ($i=1 ; $i<=3 ; $i++) {
          if (isset($_POST[$i])) {
              // here, you are on the clicked button
          }
      }
      


      请注意,我建议您为按钮提供更好的名称 (不以数字开头) - 这意味着生成您的表单,如下所示:

      <?php for ($i=1 ; $i<=3 ; $i++) { ?>
      <button type="submit" name="button_<?php echo $i ?>" value="<?php echo $i ?>" >
      </button>
      <?php } ?>
      

      并且,在提交表单时,使用类似这样的东西:

      for ($i=1 ; $i<=3 ; $i++) {
          if (isset($_POST['button_' . $i])) {
              // here, you are on the clicked button
          }
      }
      


      顺便说一句:您的 while 循环的语法不正确 - 似乎您混淆了 whilefor ;-)

      【讨论】:

      • 适用于除 IE 之外的所有应用程序。 IE(至少版本 6 及以下,我没有尝试过任何更新的版本)将为所有按钮设置值,无论它们是否被单击。几乎就像使用隐藏输入一样。
      猜你喜欢
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2014-09-02
      • 1970-01-01
      • 2014-05-21
      相关资源
      最近更新 更多