doq1969 2017-12-16 13:19
浏览 88
已采纳

在php中的foreach循环中获取项目选择的值

I want to retrieve the value of selected item while it is inside a loop to print it in javascript (alert(value)). I can't do this document.getelementbyid because it is inside a loop and the id will be repeated many times.

<?PHP
    foreach ($res->fetchAll() as $row) {
?>
<tr>
    <td>
        <?php echo $row['id']; ?>
        <input type="text" hidden value="<?php echo $row['id']; ?> " id="idartwork">
    </td>
    <td>
        <?php echo $row['name']; ?>                                     
    </td>

    <td>                
        <?php echo $row['creation_date']; ?>                            
    </td>

    <td>                
        <?php echo $row['artist']; ?>                                   
    </td>

    <td>
<?php
    if ($row['gallery'] == "") {
?>
    <select id="selectname">
        <option value=""></option>
        <option value="ghaya gallery">ghaya gallery</option>
        <option value="selma gallery">selma gallery</option>
    </select>

    <input type="button" value="affecter" onclick="affecter()">
    <input type="text" hidden value="<?php echo $row['gallery']; ?> " id="inputgallery">
    <!-- <input type="text" hidden value="--><?php //echo $row['id']; ?><!-- " id="idartwork">-->

<?php
} else {
echo $row['gallery'];
?>

<?php
}
?>
</td>

what I want to do is take the value of item select and put it in affecter() so I could print it

enter image description here

  • 写回答

3条回答 默认 最新

  • duancan1732 2017-12-16 13:24
    关注

    Use an $i variable with your foreach loop. Then add that $i to the end of each ID name, then increase the $i at the end of each loop. That way, when the loop creates the next element, each one will have a unique ID. Then you can use getElementByID in JavaScript.

    <?php 
    $i = 0;
    foreach ($res->fetchAll() as $row) { ?>
         ...
        <select id="selectname<?php echo $i; ?>">
        ...
        <input type="button" value="affecter" onclick="affecter(<?php echo $i; ?>)">
        <?php $i++;
    }  ?>
    

    Now your selects will have a unique ID of selectname0, selectname1, etc. And your JavaScript onclick function will know the $i number of that element.

    Then your JavaScript function becomes: function affecter(i) and add i to your getElementByID("selectname"+i)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败