问题
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