I have two set of radio buttons in html form button
and button1
. I am using below code to
1.keep the default value checked (
I had a similar problem recently, but had a lot more radio buttons to deal with, so I thought I'd abstract away the value checking functionality into a method that also creates the radio button itself, therefore minimising repetitive value-checking code. I've reworked mine to suit your variable names:
function createRadioOption($name, $value, $onClickMethodName, $labelText) {
$checked = '';
if ((isset($_POST[$name]) && $_POST[$name] == $value)) {
$checked = ' checked="checked"';
}
echo('<input onClick="'. $onClickMethodName .'();" type="radio" name="'. $name .'" value="'. $value .'"'. $checked .' /><label>'. $labelText .'</label>');
}
<div id="button_set1">
<?php createRadioOption('button', 'Yes', 'show_seq_lunid', 'question1'); ?>
<?php createRadioOption('button', 'No', 'show_list_lunid', 'question1'); ?>
</div>
<div id="button_set2">
<?php createRadioOption('button1', 'Yes', 'os_hpux', 'question2'); ?>
<?php createRadioOption('button1', 'No', 'os_others', 'question2'); ?>
</div>
So, the problem is you're setting the checked
value twice upon form submission, resulting in selecting either the default value (from initial form state) or the value that has been submitted.
For this to work correctly, you'd need always use PHP to append the checked
value to your radio elements, like this:
<div id="button_set1">
<input onClick="show_seq_lunid();" type="radio" name="button" value="Yes" <?php if(!isset($_POST['button']) || (isset($_POST['button']) && $_POST['button'] == 'Yes')) echo ' checked="checked"'?> /><label>question1</label>
<input onClick="show_list_lunid();" type="radio" name="button" value="No" <?php if(isset($_POST['button']) && $_POST['button'] == 'No') echo ' checked="checked"';?> /><label>answer1</label>
</div>
<div id="button_set2">
<input onClick="os_hpux();" type="radio" name="button1" value="Yes" <?php if(isset($_POST['button1']) && $_POST['button1'] == 'Yes') echo ' checked="checked"';?> /><label>question2</label>
<input onClick="os_others();" type="radio" name="button1" value="No" <?php if(!isset($_POST['button1']) || (isset($_POST['button1']) && $_POST['button1'] == 'No')) echo ' checked="checked"';?> /><label>answer2</label>
</div>
Here's a working preview: http://codepad.viper-7.com/rbInpX
Also, please note that you're using inline JavaScript notation which is normally discouraged to keep dynamic JS content separate and more manageable ;-)