Php – How to PHP determine if the user pressed the Enter key or Submit button

form-submitformsPHPsubmit

The problem I have is that I have multiple submit inputs in a single form. Each of these submit inputs has a different value and I would prefer to keep them as submit.

Whenever the user presses Enter, it is as though the topmost submit input is being pressed, and so it is causing problems for the code checking which input was clicked.

Is there a way for PHP to determine whether or not the input was clicked, or was just the input that was selected when the user pressed the Enter key?

Best Answer

You can identify which button was used provided you structure your HTML correctly

<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Preview">
<input type="submit" name="action" value="Post">

The $_POST array (or $_GET/$_REQUEST) will contain the key "action" with the value of the enacted button (whether clicked or not).

Now, "clicking" is explicitly a client-side behavior - if you want to differentiate between a click and a keypress, you'll need to add some scripting to your form to aid in that determination.

Edit

Alternatively, you can be "sneaky" and use a hidden submit that should correctly identify a key-pressed for submission, but this probably has some significant impact on accessibility.

<?php

if ( 'POST' == $_SERVER['REQUEST_METHOD'] )
{
    echo '<pre>';
    print_r( $_POST );
    echo '</pre>';
}

?>
<form method="post">

    <input type="text" name="test" value="Hello World">

    <input type="submit" name="action" value="None" style="display: none">
    <input type="submit" name="action" value="Edit">
    <input type="submit" name="action" value="Preview">
    <input type="submit" name="action" value="Post">

</form>