Jump to content

Making radio buttons sticky in a foreach array loop


sh89

Recommended Posts

Hello all. I have tried to figure out why I can't make a certain part of my code sticky. I am attempting to save the user's input for the radio button section. I am using a foreach loop for everything in my array. When I try to use if isset, it returns the last item in the array instead of what was selected by the user. Here is the code:

 

<?php
 
//Creating foreach loop for magazine selection
foreach ($magSubs as $mag => $SUB_PRICE)
{
    echo "<input type='radio' name='magtype' value='$mag' />$mag $$SUB_PRICE per month<br> ";
}
?>
 
Again, I want to make this part sticky.  

This is what I've come up with, but I still have the issue of it checking the last item in the array and not the button that was selected:

<?php
 
//Creating foreach loop for magazine selection
foreach ($magSubs as $mag => $SUB_PRICE)
{
    echo "<input type='radio' name='magtype' value='$mag' ";
    if (isset($_GET['magtype']))
    {
        echo "checked='checked'";
    }
    echo " >$mag $$SUB_PRICE per month<br>";
}
?>

Please use


tags.

 

For multiple radio buttons, the HTML name attribute needs to represent/produce an array. name="magtype[]". In your loop, you need to check for the value in the array:

 

//Creating foreach loop for magazine selection
foreach ($magSubs as $mag => $SUB_PRICE)
{
    echo "<input type='radio' name='magtype[]' value='$mag' ";
    if (isset($_GET['magtype'])) {
        if (in_array($mag, $_GET['magtype'])) {
            echo "checked='checked'";
        }
    }
    echo " >$mag $$SUB_PRICE per month<br>";
    // WHAT IS   ^^ THIS? Is that supposed to be a variable-variable?
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.