PHP / HTML:while循环使用提交按钮

时间:2017-05-19 10:19:46

标签: php html input while-loop submit

我有一个选择框,我可以在其中选择一个Project-ID并使用提交按钮将其传递给下一个表单。现在它看起来像这样:

enter image description here

这是我的代码:

 <form name="form2" action="formular3.php" method="post">

 <p><strong>Choose Project:</strong></p>
 <select name = "project_id">

 <?php
 while ($row = mysqli_fetch_array($result)) {
     echo "<option value =" . $row['project_id'] . "> Project_ID: " . $row['project_id'] . " - (" . $row['name'] . ")</option>";
 }
 ?>

 </select>

 <input type="submit" value="Send" />

 </form>

现在我想要一个列表,每行都有一个Submit-button。它应该是这样的:

enter image description here

3 个答案:

答案 0 :(得分:1)

在循环内使用提交按钮,     

 <p><strong>Choose Project:</strong></p>
 <select name = "project_id">

 <?php
 while ($row = mysqli_fetch_array($result)) {
     echo "<option value =" . $row['project_id'] . "> <input type='submit' value='Send' />Project_ID: " . $row['project_id'] . " - (" . $row['name'] . ")</option>";
 }
 ?>

 </select>



 </form>

答案 1 :(得分:1)

如果您只为每个表单发送一个选项,请完全删除选择标记。

更好的方法(并注意mysqli_fetch_assoc()而不是mysqli_fecth_array()

echo "<form name=\"form2\" action=\"formular3.php\" method=\"post\">";
    while($row=mysqli_fetch_assoc($result)){
        echo "Project_ID: {$row['project_id']} - ({$row['name']}) ";
        echo "<button name=\"project_id\" value=\"{$row['project_id']}\">Send</button>";
    }
echo "</form>";

这将在单击的按钮中提交值,而无需在html中写入如此多的表单块。您只需要使用<br>,表格单元格等来调整按钮的实际显示。

我之前的方法可行,但不是DRY:

while($row=mysqli_fetch_array($result)){
    echo "<form name=\"form2\" action=\"formular3.php\" method=\"post\">";
        echo "<input type=\"hidden\" name=\"project_id\" value=\"{$row['project_id']}\">";
        echo "Project_ID: {$row['project_id']} - ({$row['name']}) ";
        echo "<input type=\"submit\" value=\"Send\" />";
    echo "</form>";
}

答案 2 :(得分:0)

您需要停止发生当前提交事件并将提交按钮提供给ID,使用jquery点击提交您应该发布一个特定的表单。

如果点击提交,您将运行此脚本。

$(document).on('click', '#submit', function () {
    $(this).closest("form").submit();
});