lvil
lvil

Reputation: 4326

Multiple Items RadioButtons Groups

There is form with a list of items created dynamically in PHP, each has it's id(I mean database id, not the element's).
Each item has two radiobuttons (Good,Bad).
Is there a way to get in PHP an array of all items that are Bad and all item that are Good as if I was using checkboxes with names good[] and bad[] and value="id" for each item.

Is there a way to make this with radiobuttons?

<form action="some.php" method="post">
    item 1: <br/>
    <input type="radio"/>Leave<br/>
    <input type="radio"/>Delete<br/>
    item 2: <br/>
    <input type="radio"/>Leave<br/>
    <input type="radio"/>Delete<br/>
</form>

Upvotes: 0

Views: 440

Answers (2)

xdazz
xdazz

Reputation: 160833

You could make form like below:

<form action="some.php" method="post">
    <?php foreach ($ids as $i => $id) : ?>
    item <?php echo $i+1 ?>: <br/>
    <input type="radio" name="item[<?php echo $id ?>]" value="good"/>Leave<br/>
    <input type="radio" name="item[<?php echo $id ?>]" value="bad"/>Delete<br/>
    <?php endforeach; ?>
</form>

Then in some.php, $_POST['item'] will give you an array like below:

array(
    'item_id1' => 'good',
    'item_id2' => 'bad',
    .....
)

Upvotes: 0

deed02392
deed02392

Reputation: 5022

No, you can't quite do it like you would with checkboxes.

Instead you need to accept all the name=""'s of the radiogroups and loop through them, building your own array in PHP after accepting the form.

<form>
<input type="radio" name="question1" value="good" /> Good<br />
<input type="radio" name="question1" value="bad" /> bad
<input type="radio" name="question2" value="good" /> Good<br />
<input type="radio" name="question2" value="bad" /> bad
</form>

<?php
$questions = array('question1', 'question2');
foreach($questions as $q) {
    if(isset($_POST[$q])) {
        switch($_POST[$q]) {
            case 'good':
                $good += 1;
                break;
            case 'bad':
                $bad += 1;
                break;
            default:
                // invalid value
        }
    }
}

Upvotes: 1

Related Questions