How to assign unique value in hidden fields in a foreach loop

故事扮演 提交于 2019-12-12 01:43:44

问题


So my question is this: I am doing a foreach loop, and it generates a link list. Each link is having JavaScript in it, which submits the form. I want to, however, attached to EACH link a variable so that I can get the $_POST variable to see WHICH link has been clicked.

I tried a foreach loop and then something like:

foreach ($matches as $match) {
    ?>
    <div class="containerbla">
        <form>
            <h3><a href="javascript:{}" onclick="document.getElementById('matchesform').submit(); return false;"><?php echo $match->name?></a></h3>
            <?php echo $match->id; ?>
            <input type="hidden" name="matchid" value="<?php echo $match->id; ?>">
        </form>
    </div>
    <?php
}

It shows the correct user name list and the correct user ID's right below. But when I click on the user, I always get the LATEST user Id in the hidden field submitted to my view-messages php.

How can I solve that?


回答1:


foreach ($matches as $key=>$match) { ?>

                <div class="containerbla">
                    <form>
                        <h3><a href="javascript:{}" onclick="var poop = document.getElementById('matchesform'); poop.insertAdjacentHTML('<input type=\"hidden\" name=\"poop\" value=\"<?php echo $key; ?>\"/>'); poop.submit(); return false;"><?php echo $match->name?></a></h3>
                        <?php echo $match->id; ?>
                        <input type="hidden" name="matchid" value="<?php echo $match->id; ?>">
                    </form>
                </div>
            <?php
            }

Then you will be able to get the index using $matches[$_POST['poop']];

I see that you are creating a new input already, but you are not putting it in the correct form, that is why it isn't getting submitted.



来源:https://stackoverflow.com/questions/34300130/how-to-assign-unique-value-in-hidden-fields-in-a-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!