简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM