开发者

Checkboxes don't submit if unchecked, so how can I default them to true?

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 sear开发者_JAVA技巧ch 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)?


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.


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"';


If you use JQuery, do :

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

This should solve your problem.


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

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


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">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜