Page 1 of 1
How to allow only one checkbox to be checked
Posted: Fri Jun 12, 2009 8:29 am
by BaltarPHP
Hi. im using form, method=post. I have two checkboxes in the form. How can i programm php to allow only one checkbox to be checked? Right now if I check both of them - black arrow will show in both of the boxes.
Allso if i check a box and refresh the page the black affow is gone - how can i make it memorise what i have checked?
Re: How to allow only one checkbox to be checked
Posted: Fri Jun 12, 2009 9:24 am
by watson516
You might want to use radio buttons instead of checkboxes which only allow one to be selected.
Re: How to allow only one checkbox to be checked
Posted: Fri Jun 12, 2009 9:25 am
by vtvstv
Personally I think your best bet for this is to change from check box to radio buttons as they have to be mutually exclusivley selected. If you still want it to look like a checkbox you can use CSS, and put a class refrencing the CSS in your input tag eg.
Code: Select all
<form action="action.php" method="post">
<input class="someclass" type"radio" name="groupname" value="somevalue0">
<input class="someclass" type"radio" name="groupname" value="somevalue1">
</form>
There are ways to control the selection on checkboxes but the only one I know of involves a little javascript, if you want the code let me know and I will post it for you.
Laters
Kai
Re: How to allow only one checkbox to be checked
Posted: Fri Jun 12, 2009 9:30 am
by mikemike
if you're refreshing the page you have two options:
1. Save the users choice in a database using AJAX (Assuming you're not posting), this would be the preferred option if the user is logging in first.
2. Save it in a session.
With regards to only allowing one to be checked, you're probably better off with radio buttons. If you absolutely must use checkboxes then you can use PHP to check these once the form is submitted with something like:
Code: Select all
if(!empty($_POST['checkbox1']) && !empty($_POST['checkbox2'])){
echo 'Only check one checkbox please, thanks, nice one.';
}
If you need to check it before posting then you'll need JavaScript.
But like I said, what you're describing is what radio buttons are for.
Re: How to allow only one checkbox to be checked
Posted: Mon Jun 15, 2009 1:16 am
by BaltarPHP
thank you all, using radio solves the problem. But im a little beginner, can someone give me anexample how do i use session to store the value. I want the box to be checked after the refresh...