skip to Main Content

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


  1. I suspect the stumbling block here is the use of <input type="submit"> in which the examples you’ve seen so far use value="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:

    for ($index = 1; $index <= 10; $index++) {
        echo "<br>";
        echo "<label>$index</label>";
        echo "<button type="submit" name="myButton" value="$index">Submit</button>";
        echo "<br>";
    }
    

    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.)

    Login or Signup to reply.
  2. You need to add a custom name to each submit buttons.

    <?php 
    
    for ($index = 1; $index <= 10; $index++) {
        echo "<br>";
        echo "<label>$index</label>";
        echo "<input name="submit_".$index."" type="submit" value="Submit">";
        echo "<br>";
    }
    
    ?>
    

    And you can check which button has been submitted (and get their value):

    for ($index = 1; $index <= 10; $index++) {
        if (isset($_POST['submit_'.$index])) {
            //$_POST['submit_'.$index] is your submitted button
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search