Dave
Dave

Reputation: 253

Dynamic amount of submit buttons in a form

I have a form with more than one submitbutton. I'm capturing what button was clicked by giving them different names and check for the buttonname in the phpcode that's handling the form. Now I want to make these buttons dynamic and are looking for solution how to handle this.

Let's say I have an array that looks like this.

Array
(
    [0] => Array
        (
            [ID] => 1
            [Name] => Button 1
        )

    [1] => Array
        (
            [ID] => 2
            [Name] => Button 2
        )

)

Now I naturally loop through this array with something like this:

foreach($buttons as $button) 
    echo "<input type='submit' name='".$button['ID']."' value='".$button['Name']."'>";

And at the top of the page I "capture" the click by

if(isset($_POST['nameofthebutton'])) {

Here is where my problem comes. If I want to use a dynamic amount of buttons. How do I capture them here? They all will do the same thing except one value will be different, supposely the buttonid of the pressed button. How do I capture this? I don't know on before hand how many buttons will be needed so I can't write a if-statement per button. Anyone have any idea?

Upvotes: 0

Views: 643

Answers (4)

Abhishek Patel
Abhishek Patel

Reputation: 804

Create a hidden input element with say id='btnInfo'. Now add this to your button element: onClick="getBtnInfo(".$btn['ID'].")". Create a javascript function as shown below:

function getBtnInfo(var i) { var btn=Document.getElementById('btnInfo'); btn.value=i; }

And in your php script use $_POST['btnInfo'] to get id of button pressed.

Upvotes: 1

mjwunderlich
mjwunderlich

Reputation: 1035

As you're already doing, have an array with your button names:

$buttons = [['ID' => 1, 'Name' => 'some_name'], ...];
foreach($buttons as $button) {
    echo '<input type="submit" name="'.$button['Name'].'" value="'.$button['ID'].'" />';
}

Then when you receive a POST request, iterate over the button names and check if they're defined in $_POST:

foreach ($buttons as $button) {
    if (isset($_POST[ $button['Name'] ])) {
         // This submit button is in $_POST
    }
}

Upvotes: 1

mrmillod
mrmillod

Reputation: 41

echo '<input type="button" name="btn['.$button['ID'].']" value="'.$button['Name'].'" />';

Then to get your values

$buttons = $_POST['btn'];
foreach ($buttons as $id => $button) {
//
}

Upvotes: 1

n-dru
n-dru

Reputation: 9420

You can iterate over the same array you used to print this form, checking which one was clicked:

foreach($buttons as $button){
    if(isset($_POST[$button['ID']])){
        //action here...
    }
}

Upvotes: 1

Related Questions