Solved

Retain state of radio buttons

Posted on 2012-04-06
16
325 Views
Last Modified: 2012-04-08
I have a "processor" form which processes input from $_Post variables that are passed to it so that a user can edit their original input before submitting the form.

The "processor" form has 2 radio buttons allowing the user to decide to enable either the  "email" button or the "telephone" button. However, regardless of which button is chosen on the input form, the "telephone" button is continues to be enabled. Using an "echo" statement I can see that the $_Post['contactpref'] variable is correctly passing the "email" value.

Here is the code:
<?php if ($_POST['contactpref'] == "email")
      {
      echo "<input type=\"radio\" name=\"contactpref\" id=\"emailcontact\" value=\"email\" checked=\"yes\">";
      }
else
      {
      echo "<input type=\"radio\" name=\"contactpref\" id=\"emailcontact\" value=\"email\" checked=\"no\">";
      }
?>

Might someone show me where I am going wrong?
Thanks.
0
Comment
Question by:lepirtle
  • 5
  • 3
  • 3
  • +2
16 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Radio buttons and Checkboxes share a common deficiency. They are absent from the request if they are not fired by the client.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_5450-Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html

If you can tell us in plain language what you want to achieve, maybe we can help.  Cheers, ~Ray
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
Looks to me you are trying to accomplish something like this.
Notice that the initial state isn't set, so that the first time the user is faced with two unchecked radio buttons.
<html>
<body>
<?php
$checkedYes = "";
$checkedNo  = "";
if (isset($_POST['contactpref'])){
	if($_POST['contactpref'] == "email"){
		$checkedYes="checked";
	}else{
		$checkedNo ="checked";
	}
}
?>
<form name="forme1" method="post" action="">
<label>Do you want to receive annoying emails everyday?</label>
    <label>Yes<input type="radio" name="contactpref" id="emailcontactYes" value="email" <?php echo $checkedYes;?>></label>
    <label>No<input type="radio" name="contactpref" id="emailcontactNo"  value="noemail" <?php echo $checkedNo;?>></label>
    <input type="submit">
</form>
<p>You sent a form, and your answer was "<?php echo $_POST['contactpref'];?>"</p>
</body>

Open in new window

0
 
LVL 23

Expert Comment

by:basicinstinct
Comment Utility
fyi the id attribute must be UNIQUE in any html document. your radios have the same id, this is BAD.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@basicinstinct: Good point about the id attribute!  @lepirtle: You may want to use the class attribute instead -- it does not have to be unique.  If you are unsure about your markup, you can use the validation tool at http://validator.w3.org/

Also, for better or worse, computer programming is a task that requires precision.  In PHP variable names (but not class or function names) are case-sensitive so $_Post is not the same variable as $_POST.  Not sure if your script has any issues with this, but if you are unsure about your variable names, you can add error_reporting(E_ALL) to the top of the script to help you catch these sorts of things.
0
 
LVL 12

Accepted Solution

by:
Patricia Siu-Lai Ho earned 500 total points
Comment Utility
Hi

Code:

<?php if ($_POST['contactpref'] == "email")
      {
      echo "<input type=\"radio\" name=\"contactpref\" id=\"emailcontact\" value=\"email\" checked=\"checked\">";
      }
else
      {
      echo "<input type=\"radio\" name=\"contactpref\" id=\"emailcontact\" value=\"email\" >";
      }
?>

Open in new window


For the radio buttons, if you want it to be checked, use checked="checked".

If it is unchecked, just dont put the checked="" into the attribute.  

checked="yes" and "no" or "checked" are treated as flagged the radio button.

Hope it helps

Patricia / pslh
0
 

Author Closing Comment

by:lepirtle
Comment Utility
To all: Thank you very much. You have increased my knowledge and pointed-out errors that I didn't know existed.

pslh,
Thanks very much for the solution. It works perfectly!

Ray_Paseur and basicinstinct,
I appreciate the above replies and especially the long article you provided about Radio buttons and Checkboxes sharing a common deficiency. I want to experiment with that as soon as I finish coding this project. I was unaware of the validation tools (and have already ran it on a couple of my pages) or the use of "id". Strangely to me, I have used identical "ids" for radio buttons in many scripts I have written and none have caused problems. However, you are the experts so I am changing my procedure to follow your coding recommendations.

designatedinitializer,
I understand what you are doing and it seems to be the similar principal as plsh furnished however plsh's uses almost all my existing code with only very minor changes to allow the script to run correctly.
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
lepirtle:
If someone offers me a Ferrari for the price of a mule, I go for the Ferrari. But that's just me.
0
 
LVL 12

Expert Comment

by:Patricia Siu-Lai Ho
Comment Utility
Glad it helped.

This is the first question that I got graded A answered question after 10 years not being in EE and this is the first day I am back.  

Happy Easter all.
Patricia / pslh
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@lepirtle: I am still mystified.  In the code with the original question, I find the variable $_POST['contactpref'] being used in what appears to be an attempt to generate an HTML form.  What I don't get (and why I asked you to tell us in plain language what you want to achieve) is how it could make sense to use a data element that your script already knew to generate a form asking the client to provide input, when the script already has the exact same field in the existing POST array.  It seems to me like the design pattern may be confused, but maybe I am missing something.  In any case, this reference is a pretty good one and can help you avoid things like "checked=yes."
http://www.w3schools.com/tags/tag_input.asp

@pslh: Welcome back and Happy Easter to you, too!
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
Your attention please:

The accepted solution will only cause you more trouble:
1. The fact that the IDs are the same in both input fields spells 'trouble' if you later decide to use javascript on the page;
2. The fact that both radio buttons output the same value renders the form useless.

...which in turn renders the 'if' clause useless, for $_POST['contactpref'] will always be 'email'...
0
 

Author Comment

by:lepirtle
Comment Utility
Ray_Paseur,
My apologies if I didn't make myself clear. When posting a question I try to be as brief as possible without leaving out the important details required to answer the question. Next time I will provide more background details. And I have taken a look at the reference URL that you provided. So thanks again.
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
hello... did I forget to turn my invisibility field off?...
0
 

Author Comment

by:lepirtle
Comment Utility
designatedinitializer,
I did change my coding to eliminate the id's even though I don't use them in the page's javascript and the value of both radio button does produce the same value, it is their "checked" vs non-checked state that I needed to display properly and that display depends on the checked state that is being passed to that form. So the following code works perfectly as follows:
<?php if ($_POST['contactpref'] == "telephone")
{
      echo "<input type=\"radio\" name=\"contactpref\" value=\"telephone\" checked=\"yes\" />";
}
else
{
      echo "<input type=\"radio\" name=\"contactpref\" value=\"telephone\" />";
}
?>
0
 
LVL 23

Expert Comment

by:basicinstinct
Comment Utility
designatedinitializer is right tho, it does seem a little odd to have the same value for both radio buttons. it is like asking "do you want to choose telephone or telephone" - makes no sense. no matter what the user choses the server will get this in the http post:

contactpref=telephone
0
 
LVL 7

Expert Comment

by:designatedinitializer
Comment Utility
*sigh*
lepirtle: test it thoroughly. Then tell me it works perfectly.
I find it very funny that now you are trying to teach me what the 'checked' attribute is for...
0
 
LVL 12

Expert Comment

by:Patricia Siu-Lai Ho
Comment Utility
Hi,

lepirtle using a if else function,

the radio button is in default checked and inside the box the default value is email or Telephone whatever lepirtle wants to tell user to input.
 
(x) [ email ]

But if the user not entering email/telephone, they just type whatever the user wants, then they posted the form.

Then it comes to the checkpoint, as the input is not equal to "email", then after refresh or back to the same form, the radio button is now unchecked and look like the following.

( ) [ email ]

And user needs to enter something else and/or just checked the box and/or continue to post the form.

His original problem is  in default :

( ) [ email ]

He wants to check the radio button but he cant by his original codes.

When the first input is something else and not the email, after refresh or back to same page,

it looks like this

(x) [ email ]

That is not matched with his idea.


Patricia / pslh
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now