根据查询结果循环将 id 放在输入上并在 td 中选择标签

为每个输入标签分配 id 并根据查询结果在 tr 中选择标签


我尝试了这样的代码,将 id 放入输入标签并选择标签


        <table id="myTable">

          <thead>

               <th>Progress</th>

               <th>Amount</th>

               <th>Action</th>

          </thead>

          <tbody>

            <?php $qry = "SELECT * FROM trade";

                  foreach($conn->query($qry) as $data){

            ?>

            <form action="update.php" method="post">

            <tr>

               <td><select name="progress" id="select_progress" onclick="changeSetting()">

                       <option value="Partial">Partial</option>

                       <option value="Full">Full</option>

                   </select></td>

               <td><input type="number" name="amount" id="amount"></td>

               <td><input type="submit" name="update" value="Update"></td>

               <input type="hidden" name="tradeid" value="<?php echo $data['tradeID'];?>">

            </tr>

            </form>

            <?php }?>

          </tbody>

         </table>


现在我像这样编写了 javascript:


        function changeSetting(){

             var selectValue = document.getElementById("select_progress").value;

             var amountValue = document.getElementById("amount");

             if(selectValue.value === "Partial"){

                   amountValue.required = true;

             }else if(selectValue.value === "Full"){

                   amountValue.required = false;

             }

        }

第一行似乎做得很好,但第二行不应用我写的 javascript。欢迎任何有关如何解决此问题的建议。我知道,每个元素的 id 应该是唯一的,但是如果我的查询中有大约 50 个结果,我不知道如何将 id 放在每个输入上并在我的表中选择标签。非常感谢任何建议或帮助。


白板的微信
浏览 158回答 1
1回答

月关宝盒

你所有的元素都有相同的id值,所以当你尝试getElementById它时总是返回第一个。解决此问题的一种方法是将tradeID值添加到每个元素的id值以区分它们。例如:<td><select name="progress" id="select_progress<?php echo $data['tradeID'];?>" onchange="changeSetting(<?php echo $data['tradeID'];?>)">&nbsp; &nbsp; &nbsp; <option value="Partial">Partial</option>&nbsp; &nbsp; &nbsp; <option value="Full">Full</option>&nbsp; &nbsp; </select></td>&nbsp;<td><input type="number" name="amount" id="amount<?php echo $data['tradeID'];?>"></td>&nbsp;<td><input type="submit" name="update" value="Update"></td>然后你会修改你的JS:function changeSetting(id){&nbsp; var selectValue = document.getElementById("select_progress" + id).value;&nbsp; var amountValue = document.getElementById("amount" + id);&nbsp; if(selectValue === "Partial"){&nbsp; &nbsp; amountValue.required = true;&nbsp; }else if(selectValue === "Full"){&nbsp; &nbsp; &nbsp;amountValue.required = false;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP