b p
b p

Reputation: 9

HTML - PHP More than one multiple choice questn in a form, can select only one radio button.

Newbie here. I am trying to display more than one Multiple questions on a form with multiple choice answers displayed as radio buttons. A user should be able to select one answer(radion button) per question.

My problem is that once I display the questions and the answers, I can only select one radio button on the form(not per question). In the code below, qid is the question Id and aid is the answer Id. For each question retrieved from the database, the radio button group would get the question number assigned to the name.

For ex: question 1 has 4 multiple choice answers with name = 1 , question 2 has 4 multiple choice answers with name = 2 and so on.

So when the user selects an answer for question 1 and picks an answer to question 2, the selected answer for question 1 is cleared.

<body style="margin: 100px;">
    <?php foreach ($questions as $question) : ?>
        <small>(<?php echo $question['qid']; ?>)</small>
        <strong><?php echo $question['qdesc']; ?></strong>

        <ol>
           <?php foreach ($answers[$question['qid']] as $answer) : ?>
                <li><label><input type="radio" name=$question['qid'] value=$answer['aid']><?php  echo $answer['adesc']; ?></label></li>               
           <?php endforeach; ?>
        </ol>
    <?php endforeach; ?>
</body>

Upvotes: 0

Views: 2477

Answers (2)

Frankey
Frankey

Reputation: 3757

as a small addition to the answer above.

<li>
<label for="qid_<?php echo $question['qid']; ?>">
<input type="radio" id="qid_<?php echo $question['qid']; ?>" name="q_<?php echo $question['qid']; ?>" value="<?php echo $answer['aid']; ?>">
<?php  echo $answer['adesc']; ?>
</label>
</li> 

now you can click on the text after the input in the label and the radio button will be selected.

label attribute [for] corresponding to the input attribute [id] within it

Upvotes: 1

MrCode
MrCode

Reputation: 64526

Your radio button name has PHP code that is missing the opening and closing PHP tags (also missing quotes):

<li><label><input type="radio" name="q_<?php echo $question['qid']; ?>" value="<?php echo $answer['aid']; ?>"><?php  echo $answer['adesc']; ?></label></li>               

You might also want to include a prefix (as above) so that the names are not just numbers.

Because your radio groups all had the same name, it meant that were all treated as a single group and so only lets you select one.

Upvotes: 1

Related Questions