Search code examples
phphtmlinputradio-buttonchecked

to checked whether one of the radio button is checked or not from a particular radio group


All the inputs have the same name as option<?=$x?> for each loop but always the input with type=hidden of the last line overrides all of them although one of the radio buttons with same name option<?=$x?> is selected

Is there anyway so that I can check whether anyone out of four radios of above is chosen or not, if not then I have to pass the last input instead of them

<input type="radio" name="option<?=$x?>" value="<?=$chioce[0].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[0]?>
<input type="radio" name="option<?=$x?>" value="<?=$chioce[1].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[1]?>
<input type="radio" name="option<?=$x?>" value="<?=$chioce[2].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[2]?>
<input type="radio" name="option<?=$x?>" value="<?=$chioce[3].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[3]?>

<input type="hidden" name="option<?=$x?>" value="null;<?=$data['id'].';'.$data['subject']?>">

Solution

  • You can try this

    <input type="radio" name="option[<?=$x?>]['radio']" value="<?=$chioce[0].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[0]?>
    <input type="radio" name="option[<?=$x?>]['radio']" value="<?=$chioce[1].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[1]?>
    <input type="radio" name="option[<?=$x?>]['radio']" value="<?=$chioce[2].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[2]?>
    <input type="radio" name="option[<?=$x?>]['radio']" value="<?=$chioce[3].';'.$data['id'].';'.$data['subject']?>" ><?=$chioce[3]?>
    
    <input type="hidden" name="option[<?=$x?>]['hidden']" value="null;<?=$data['id'].';'.$data['subject']?>">`
    

    Now when you post you will get option array

    $options = $_POST['option'];
    $radioValue = $options[$x]['radio'];
    $hiddenValue = $options[$x]['hidden'];
    

    You can read value like this

    $optionValue = isset($options[$x]['radio']) ? $options[$x]['radio'] : $options[$x]['hidden'];
    

    Hope it may help you