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 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader