Pom Canys
Pom Canys

Reputation: 379

Using dynamic radio buttons

If you want to create a dynamic form using text fields, it's easy, since you can use arrays, kind of like this:

<input type="text" name="text[]">
<input type="text" name="text[]">

In PHP var_dump($_GET['text']); will just give you what you need. But what if I want some dynamic radio buttons?

What if I had some categories like this:

Color1: 
<input value="red" type="radio" name="color[]">
<input value="blue" type="radio" name="color[]">

Color2:
<input value="orange" type="radio" name="color[]">
<input value="yellow" type="radio" name="color[]">

Color3:
<input value="black" type="radio" name="color[]">
<input value="white" type="radio" name="color[]">

For now var_dump() returns only 1 value from all 6 fields. Also you can select only one radio button, which makes absolutely sense.

The result that I am looking for is an array that returns e.g.: red, yellow, white (one color from each category)

I think the solution would be to pass an increasing number behind the name attribute. But How would I return their values with PHP?

Upvotes: 0

Views: 87

Answers (3)

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

you can do it by giving name to radio group naming like below

Color1: 
<input value="red" type="radio" name="Color1[]">
<input value="blue" type="radio" name="Color1[]">

Color2:
<input value="orange" type="radio" name="Color2[]">
<input value="yellow" type="radio" name="Color2[]">

Color3:
<input value="black" type="radio" name="Color3[]">
<input value="white" type="radio" name="Color3[]">

Upvotes: 1

Amit Rajput
Amit Rajput

Reputation: 2059

Just do like this:

 Color1: 
<input value="red" type="radio" name="color[Color1]">
<input value="blue" type="radio" name="color[Color1]">

Color2:
<input value="orange" type="radio" name="color[Color2]">
<input value="yellow" type="radio" name="color[Color2]">

Color3:
<input value="black" type="radio" name="color[Color3]">
<input value="white" type="radio" name="color[Color3]">

Output will be like:

[color] => Array
        (
            [Color1] => blue
            [Color2] => yellow
            [Color3] => white
        )

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31739

Name the fields like -

Color1: 
<input value="red" type="radio" name="color[1]">
<input value="blue" type="radio" name="color[1]">

Color2:
<input value="orange" type="radio" name="color[2]">
<input value="yellow" type="radio" name="color[2]">

Color3:
<input value="black" type="radio" name="color[3]">
<input value="white" type="radio" name="color[3]">

It will return a multidimensional array having 3 sub arrays containing the colors. The indexes will be -

1 => color1
2 => color2
3 => color3

Upvotes: 2

Related Questions