Reputation: 35
I have a situation where there are 5 radio buttons, one default checked on page open. These radio buttons represent 5 categories. Within each category are several subcategory submit buttons. The subcategory buttons are hidden except for the ones in the category that is currently selected at radio button.
I want users to be able to select a category using the radio button then select from one of the subcategories, but on page refresh (from the $_POST request), i want the radio button of the 'current' category to remain checked. As it stands now the page refreshes with the submission of a subcategory submit and the radio is default checked to the first radio button category.
I have javascript coordinating the radio hide container action, so the form tags must seemingly cover all five radio buttons and all five radio buttons have the same name, which can't be changed due to my underlying javascript. So i can't simply change each radio's name and code in PHP accordingly with sessions and such.
i actually got the category to stay on $_POST submission by using a session variable in the radio tag where you would find checked , but i had to encapsulate each radio and respective subcategory section within its own form tags. This causes problems with the javascript of course, and the radio buttons, once pushed, will not be able to be pushed again.
Is there a way to resolve this using php?
Upvotes: 0
Views: 1125
Reputation: 16359
I've had to do this with classes, its a little cumbersome. On page load, pull the checked item value into a variable ($val in this case). and have this inline for each input item:
<input type="radio" ... value="someval" <?php $x = ($val=='someval' ? 'checked="checked"' : ''); echo $x; ?> />
Like I said, cumbersome, but it checks the correct item. The only thing is that your first item will need to have some more if logic, since it will be defaulting to be checked if no value is chosen already.
<input type="radio" ... value="firstval" <?php $x = ((empty($val)) || ($val=='firstval')) ? 'checked="checked"' : ''; echo $x; ?> /> //removed extra bracket
You can prettify it as needed, that was just for inline.
Upvotes: 2