Hi,
I have dynamically created radio buttons.
$i=1;
<input type="radio" name="qtn-$i" value="yes">
$i++; Now how to get the values of these buttons using post method?
Hi,
I have dynamically created radio buttons.
$i=1;
<input type="radio" name="qtn-$i" value="yes">
$i++; Now how to get the values of these buttons using post method?
Short clarification and a safe pattern to handle many dynamically generated radio groups.
As showed, giving each input a unique name (qtn-1, qtn-2, ...) makes every radio independent. As noted, options that belong to the same question must share the same name so only one can be chosen. A convenient PHP pattern is to name groups as an array (for example qtn[1], qtn[2]), so PHP collects all answers into $_POST['qtn'] keyed by question id.
Example generation (server-side):
<?php
$count = 5; // number of questions
for ($i = 1; $i <= $count; $i++) {
echo '<label>Q' . $i . '</label>';
echo '<input type="radio" name="qtn[' . $i . ']" value="yes"> Yes ';
echo '<input type="radio" name="qtn[' . $i . ']" value="no"> No ';
}
?> Example processing:
<?php
// iterate submitted answers (safe output)
if (!empty($_POST['qtn'])) {
foreach ($_POST['qtn'] as $qid => $answer) {
$safe = htmlspecialchars($answer, ENT_QUOTES, 'UTF-8');
echo "Question $qid: $safe<br>";
}
}
// to detect unanswered ones use a loop 1..$count and check isset($_POST['qtn'][$i])
?> Troubleshooting notes:
$ans = $_POST['qtn'][$i] ?? 'no answer';.print_r($_POST) while debugging.This array-naming approach scales well for variable question counts and keeps server-side handling straightforward.
Are you using PHP? 'Cos there is no way our going to get the radio buttons appear on the screen without the echo statement. You code above is going to go into an infinite loop, provided of course you put in a loop statement in the first place.
Also the way you have created the radio buttons with different names, will be in such a way that you can select all the radio buttons at a time.
Enough of my criticism, coming down to the actual code part.
<form method="post">
<?
echo $_POST['qtn'];
for ($i=1;$i<=4;$i++){
echo "<input type='radio' name='qtn' value='$i'>";
}
?>
<input type="submit">
</form> The above code is a simple way you can get the values of the radio buttons using a POST method. The name of the radio buttons need to be the same but the value will change.
Please do let me know if you need anything else.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.