views:

713

answers:

3

how can i process all radio buttons from the page?

<input type="radio" name="radio_1" value="some" />
<input type="radio" name="radio_1" value="some other" />

<input type="radio" name="radio_2" value="some" />
<input type="radio" name="radio_2" value="some other" />

this buttons will be added dynamically so i will not know the radio buttons name(and also the number of the buttons). Is there a way to get all radio values, with a for loop or something like this? thanks

+1  A: 

Since the browser will just change all your input to HTTP-formatted form data, you won't be able to tell what data is from a radio button versus a text box or other input.

If the naming convention is the same as your example, just loop until you don't find a value:

<?
  for ($idx = 1; $idx <= 1000; $idx++) {
    if (isset($_REQUEST["radio_$idx"])) {
      // handle value
    }
  }
?>

EDIT Alternatively, if your form is generated dynamically, you could write the number of radio buttons it created as a hidden field in the form.

If you are able to alter the form that is being generated, you could write a hidden input that provided a list of all the radio buttons that you want to look for. As you are writing the radio buttons, just make a semi-colon-separated list of all the names that you make. When you are done, write that to a hidden input. Something like this:

On the source form:

<input type="hidden" name="radio_button_list" value="some_value;other_value" />

Then in your handler:

<?
  $list = explode(';', $_REQUEST['radio_button_list']);
  foreach ($list as $name) {
    $value = $_REQUEST[$name];
    // handle name & value
  }
?>
jheddings
I guess you mean $_POST and looping isn't really efficient. Better loop over $_POST and check for the pattern
jitter
True, it could be either $_GET or _POST, depending on how the form was created. In either case, the result is the same.
jheddings
or $_REQUEST if you don't care how it was received.
Jason
ok, but if the radio names are totally different like "some_value", "other_value", "even_more_values". can i do something about that?
kmunky
You'll need to have something that you can key on to know that you are looking at a radio button name, as opposed to some other input type.
jheddings
A: 

jheddings' example says it all. However, you will never get the names / values of all buttons - just the selected one from each group. If you need literally all values, you will have to use Javascript.

Pekka
Good point... I did assume the OP wanted all selected values, not possible values.
jheddings
yap...just the selected values
kmunky
+1  A: 

Use a foreach loop

<?php
foreach ( $_POST as $key => $val )
    echo "$key -> $val\n";
?>

$key will be the name of the selected option and $val, well, the value.

Oz