Trying to find out which button the user has pressed. I want to get the value that is in the form-label when the corresponding button is pressed. Is this possible? Thanks
index.php
<html>
<form action="./process.php" method="post">
<?php
for ($index = 1; $index <= 10; $index++) {
echo "<br>";
echo "<label>$index</label>";
echo "<input type="submit" value="Submit">";
echo "<br>";
}
?>
</form>
</html>
process.php
<?php
# I want to print the number here? So if the button next to number 1 was pressed it would be 1 printed here.
?>
Thanks
2
Answers
I suspect the stumbling block here is the use of
<input type="submit">
in which the examples you’ve seen so far usevalue="Submit"
to set the text of the button.But if you use a
<button type="submit">
instead, you can set the text within the element and control its value separately:Whichever button is clicked would be the only one posting its value to the server, and would be observable in
$_POST['myButton']
.(As an aside…
type="submit"
is the default and doesn’t necessarily need to be specified explicitly, but I personally consider it good practice to be explicit in these cases because we’ve often seen bugs/confusion when no type is specified and a form submit is not the intended action, but rather some client-side handler is.)You need to add a custom name to each submit buttons.
And you can check which button has been submitted (and get their value):