Forum Moderators: coopster

Message Too Old, No Replies

Validate radio buttons

checking to see that radio button is selected on a form

         

lag062

5:27 pm on Apr 4, 2005 (gmt 0)

10+ Year Member



i am trying to create an PHP form that checks to see if a radio button as been selected before submitting information.

there are two radio buttons, and the user needs to pick one.

sorry im very new to this and any help would be very much appreciated.

Thanks you in advanced

lag062

5:29 pm on Apr 4, 2005 (gmt 0)

10+ Year Member



also if a radio button is not selected then i need the script to return an error alertin the user.

Any ideas please?

jatar_k

6:53 pm on Apr 4, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld lag062,

I am assuming that your form is submitted using the post method. You would do the tests for values etc on the page that is specified in the 'action' of the form.

if you had a radio button such as these 2

<input type="radio" name="choose" value="one">
<input type="radio" name="choose" value="two">

now when this form is posted to your script these variables will become available in the $_POST array. A good way to look at what you have available and to understand how the $_POST array works is to do this in your script

echo '<pre>';
print_r($_POST);
echo '</pre>';

if you have this for now, try submitting your form a bunch of times to see what it looks like. Try once with one radio selected, once with the second and once with none at all and see what your options might be for testing that value.

a function that might come in handy is isset [php.net]. That and an if statement and you should be laughing.

ramoneguru

3:59 am on Apr 5, 2005 (gmt 0)

10+ Year Member



If you don't feel like error checking the buttons

<input type="radio" name="choose" value="one" checked>
<input type="radio" name="choose" value="two">

--Nick

sitz

4:06 am on Apr 5, 2005 (gmt 0)

10+ Year Member



Note that you can also do this in javascript; doing so offloads the basic input validation to the browser, which makes it faster (making the user happier) and results in one less hit coming to your servers (effectively increasing your capacity). Note that input validation on javascript is NO SUBSTITUTE for having sanity-checking on the server-side as well, since users can disable javascript, but having an initial check in javascript certainly doesn't hurt. Basically, I recommend using both; one so that the user gets things right, and one to keep them from trying to pull something shady. =)