Reputation: 161
Ok, im unsure on how to explain what i want (probably why i cant figure out how to do it) but basically, I have the following html form:
<p class="ratingButtons">
<input type="radio" class="spacing" name="moRating1" value="1">1
<input type="radio" class="spacing" name="moRating1" value="2">2
<input type="radio" class="spacing" name="moRating1" value="3">3
<input type="radio" class="spacing" name="moRating1" value="4">4
<input type="radio" class="spacing" name="moRating1" value="5">5
<input type="radio" class="spacing" name="moRating1" value="6">6
</p>
What i'm wanting to do is some sort of PHP loop to print whichever one is selected, then turn it into a function so i could reuse it for different questions (like the one below) therefore cutting down on the amount of HTML is used..
<p class="ratingButtons">
<input type="radio" class="spacing" name="moRating2" value="1">1
<input type="radio" class="spacing" name="moRating2" value="2">2
<input type="radio" class="spacing" name="moRating2" value="3">3
<input type="radio" class="spacing" name="moRating2" value="4">4
<input type="radio" class="spacing" name="moRating2" value="5">5
<input type="radio" class="spacing" name="moRating2" value="6">6
</p>
Any ideas? or tips, im pretty new to php so as newbie friendly as possible please! Thanks in advance!
Upvotes: 0
Views: 2280
Reputation: 2622
$options- No of options you want
$sel_val- Selected value of the vote to show it selected
$name - Name From which you want the values in the post
function rating_buttons($options,$sel_value,$name)
{
$output ='<p class="ratingButtons">';
for($i=0;$i<$options;$i++)
{
$value=$i+1;
$output .= '<input type="radio" class="spacing" ';
if($sel_value==$value)
$output .='checked="Checked"';
else
$output .='';
$output .='name="'.$name.'" value="'.$value.'">'.$value;
}
$output .='</p>';
echo $output;
}
rating_buttons(5,3,'abc');
Upvotes: 1
Reputation: 1231
It's so easy:
<?php
function radio_selected($selected,$array){
$len=count($array);
for($i=0;$i < $len;++$i){
$num=$i+1;
$class=($selected==$array[$i])?'checked="checked"':'';
$a.='<input type="radio" class="spacing" name="moRating'.$num.'" value="'.$num.'"'.$class.'> '.$num;
}
return $a;
}
// --- And you can use it now
$array=Array('a','b','c');
$selected=$_POST['b']; // For example b
echo radio_selected($selected,$array);
?>
Upvotes: 1
Reputation: 43552
Your function could look something like this:
function generateRadioButtons($name, $values = 6) {
$o = '<p class="ratingButtons">' . "\n";
for ($v = 1; $v <= $values; $v++) {
$selected = !empty($_POST[$name]) && $_POST[$name] == $v ? ' checked="checked"' : '';
$o.= '<input type="radio" class="spacing" name="' . $name . '" value="' . $v . '"' . $selected . '>' . $v . "\n";
}
$o.= '</p>' . "\n";
return $o;
}
And with this function, you can easily output your options:
echo generateRadioButtons('moRating1');
echo generateRadioButtons('moRating2');
Demo.
Upvotes: 3