How to set sessions for checkboxes
Hi,
I have an application and to select the yes or no option i have set an checkboxes, and for that i decided to keep sessions for that,whenever checkbox. Whenever i will check the option the sessions should be generated for the same, I have written the following code for the sessions to get executed.
Following is the code
Code:
<input id="repair" name="repair" type="checkbox" value="Repairs"checked="<?=$_SESSION[repair]?>" /> Repairs
this session works fine when i have input as a type text.
can you give a hint please?
Cheers,
Re: How to set sessions for checkboxes
1) Try not to use short tags, use the full <?php echo $_SESSION ['repair'] ?> instead.
2) The HTML (not XHTML) way of defining a checkbox as checked was/is just by using the word 'checked' as oppose to the XHTML way which is checked="checked". For compatibility reasons, even if checked="" is set with no value the attribute 'checked' becomes true. If you want the checkbox to be unchecked you cant even have the empty checked=" "attribute in the tag.
Re: How to set sessions for checkboxes
PHP checkboxes have a quirk in that if the checkbox is clear (false), browsers are not required to submit the control. If the control is set, the control is submitted as "control_name=control_name", but in the case of a clear checkbox, nothing is expected to be submitted.
Accordingly, it is import to set the property backing the checkbox to false when a form is rendered. If the checkbox submits back clear, it will remain false, if the form submits back, the field can be set to true to reflect the change.
However, if the form is being held in session scope, prematurely setting the value to false can be dangerous. If the form is never submitted back, the value will remain false. If the form is later committed to persistent store, an inadvertent change in state will occur.
Re: How to set sessions for checkboxes
on each checkbox, you would have to individually check that session variables value, like this:
<input type="checkbox" name="chk1A" <%if Session("checkVar") = "1A" then Response.Write "checked"%> />This is checkbox 1A
<input type="checkbox" name="chk1B" <%if Session("checkVar") = "1B" then Response.Write "checked"%> />This is checkbox 1B
<input type="checkbox" name="chk1C" <%if Session("checkVar") = "1C" then Response.Write "checked"%> />This is checkbox 1C
if you were to have multiple checkbox values stored in the session variable, you would need to change your IF statement to:
<input type="checkbox" name="chk1A" <%if InStr( Session("checkVar"), "1A" ) > 0 then Response.Write "checked"%> />This ia checkbox 1A
This basically checks to see if the string "1A" is in the session variable, and if so, it'll check the checkbox.