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 镍氢电池充电器设计实物使用原理
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?