aceslowman
aceslowman

Reputation: 631

Submitting multiple variables with one input

foreach($rates as $item){    
    if ($item->disabled == false){
        echo '<input type="radio" name="rate" id="membership" required="yes" message="Please select your membership type."  value="' . $item->rate . '"><input type="hidden" name="membership" value="' . $item->membership . '" >';
    }
}

This is probably pretty simple, but the issue that I'm having is that I can't get $item->membership to submit with $item->rate. For example when somebody selects the '125' rate, it should also submit 'Student' or whatever. When I do submit the form though, it submits the last $item->membership in the series instead of the one that is tied to it's rate... Any help would be appreciated, I'm sure I'm overthinking this.

Thanks

Upvotes: 2

Views: 4208

Answers (2)

Telvin Nguyen
Telvin Nguyen

Reputation: 3559

When you submit an form, hidden field and radio button are independent elements regardless how you wrap them together.

Here is my solution to pass multiple variables for each radio button

view:

<form method="post" action="your_post_file.php" >
    <?php $i = 1;  foreach($rates as $item){?>
        <input type="radio" name="rates[]" value="<?php echo $i?>" /><?php echo $item->rate?>
        <input type="hidden" name="rate<?php echo $i?>" value="<?php echo $item->rate?>" />
        <input type="hidden" name="membership<?php echo $i?>" value="<?php echo $item->member_id?>" />
    <?php $i++;}?>

    <input type="submit" />
</form>

on the your_post_file.php

if(isset($_POST['rates'])){
            if(is_array($_POST['rates'])){

                $index = $_POST['rates'][0]; //return the index of selected radio button

                $rate =  $_POST['rate' . $index];
                $membership_id =  $_POST['membership' . $index];

                //print out the result
                var_dump($rate);
                var_dump($membership_id);

            }
        }

Bingo, you get what you want, even you want more the value for each rate, just add more hidden field with same given format, such as first name, last name, or anything else.

Upvotes: 1

t0mppa
t0mppa

Reputation: 4078

Because they all have the same name attribute, so they set the same variable multiple times and thus the last one is what you always get. Try giving all the hidden inputs unique names, so you can get the membership you want. HTML forms aren't smart enough to pick only the hidden input next to the radio button, they all get posted.

Upvotes: 3

Related Questions