Jump to content

Making radio buttons sticky in a foreach array loop


sh89
Go to solution Solved by DavidAM,

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.  
Link to comment
Share on other sites

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>";
}
?>
Link to comment
Share on other sites

  • Solution

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?
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.