tags:

views:

133

answers:

5

I have a form with a checkbox that's used to filter some search results.

The form action is GET so that the users can navigate back to the search results without having to OK the post data request message.

I want one of the checkboxes to default to true. This in itself is not a problem of course, it's simple HTML. However, it's the PHP that powers it that I'm struggling to figure out.

When the user visits the page for the first time, there won't be any GET variables set, meaning thisCheckbox would be unset and all the relevant checks would evaluate to false. Meaning I can't do:

#this returns a false negative
if (isset($_GET['thisCheckbox'])) echo 'checked="checked"';

If the user explicity ticks the checkbox and submits, then it's fine, because $_GET['thisCheckbox'] will be true.

Is there a way of getting round this (without using radio buttons)?

+2  A: 

You want to check if it is set, and if it is not, check for other variables that are indicative of a request having taken place.

Williham Totland
bcmcfc
That would be a sollution, yes. But if you have a text field or anything else of the kind; that'll do just fine, as they are always successful.
Williham Totland
Of course! `self::slap()`
bcmcfc
That should probably be `$this->slap($this);` instead :P
BoltClock
@BoltClock's a Unicorn I'm currently `static`!
bcmcfc
If the get is performed by a form submit (which I suppose), the value of the submit button is sent as a request parameter as well. So you can check if you're coming from a request by checking that paramter. Which is probably why that is the behavior in the first place, so I suggest you use that.
Joeri Hendrickx
+2  A: 

Not very nice, but what about introducing a hidden field $_GET['filterApplied']. If the user submits the form, this field is set. Than you can do it like


if (!isset($_GET['filterApplied'] || isset($_GET['thisCheckbox'])) echo 'checked="checked"';
hacksteak25
A: 

If you use JQuery, do :

$(document).ready(function(){
$("#thisCheckbox").attr("checked",true);
});

This should solve your problem.

Siva Gopal
OP says, "I want one of the checkboxes to default to true. This in itself is not a problem of course, it's simple HTML." So actually showing the checkbox to be checked is not a problem here. OP is looking for a way to set a server-side script variable which HTML and JS can't control.
BoltClock
A: 

If you don't use $_GET for anything else, you can also do

if( empty( $_GET ) || isset( $_GET['thisCheckbox'] ) ) {
    echo 'checked="checked"';
}
Aether
A: 

This is an ugly approach, but it works. Add a hidden input field with the same name above your checkbox.

<input type="hidden" name="thisCheckbox" value="0">
<input type="checkbox" name="thisCheckbox" value="1">
Johan