I have block of code which is loaded while clicking a particular button through Ajax.
I have given each input a name like txtname[]
, country[]
and also radiobtn[]
.
The problem is, when I am filling these 3 fields twice and selecting a radio button in the second iteration and then printing post array through print_r($_POST);
is showing the following results below:
[txtname] => Array ( [0] => xyz[1] => abc)[country] => Array ( [0] => India[1] => United Kingdom ) [radiobtn] => Array ( [0] => true )
It shouldn't show like:
[txtname] => Array ( [0] => xyz[1] => abc)[country] => Array ( [0] => India[1] => United Kingdom ) [radiobtn] => Array ( [0] => ""[1] => true)
So how to go about knowing which iteration radio button is selected? Any help appreciated.
HTML
<input type="radio" name="radiobtn[]" value="true">
<input type="text" name="txtname[]" >
<select name="country[]">
<option value="country" selected="selected">Select Country</option>
<option value="United States" >India </option>
<option value="United Kingdom">United Kingdom</option>
</select>
You are expecting two values from radiobtn
which is of type radio
. The radio button type is supposed to force the selection of only one item, therefore the radiobtn[]
array you are trying to populate will always contain only one value, which is true
. And that is correctly shown by the result:
[radiobtn] => Array ( [0] => true )
Your radiobtn[]
array is overwritten at each iteration, leading to only the last result being stored in the $_POST
global variable. Therefore the []
in radiobtn[]
is pointless since there will never be more than one value.
For multiple selections you may want to take a look at type="checkbox"
which can store multiple values for the same name. An example would be:
<input type="checkbox" name="btn[]" value="A">A</input>
<input type="checkbox" name="btn[]" value="B">B</input>
<input type="checkbox" name="btn[]" value="C">C</input>