简体   繁体   中英

Responsive Checkbox or Toggle for boolean value

I'm making a CMS for my website and I have columns in my blogs database for whether or not the blog post is visible or not, and if comments are enabled or not.

At the moment in my form I've got

            <div class="input-group">
                <span class="input-group-addon">Comments</span>
                <input type="text" class="form-control" name="blogcomments" id="blogcomments" placeholder="1 or 0" required maxlength="1" value="<?php echo ($data['blog']->blogcomments)?>">
            </div>

so if I'm editing a blog it will already pull the value, otherwise it'll just show the placeholder. I can then either type 1 or 0 and submit.

What I want to do it have a checkbox or a toggle (I was looking at bootstrap-switch), but I'm really not sure how to implement this. I guess I could just have a default value in the column of 0 and have the checkbox value to 1? I don't really like that idea though.

I've also no idea how to check the existing value (if there is one) and set the checkbox/button/whatever accordingly (so if the value is already 1 in the column it would be checked already). I'm guessing at this point I'd need javascript?

Use the checkbox like below:

 <div class="input-group"> <span class="input-group-addon">Comments</span> <input type="checkbox" class="form-control" name="blogcomments" id="blogcomments" required value="1"> </div> 

If the checkbox is selected, it will return "1" otherwise, it will return "null".

Decided to use bootstrap-switch

            <div class="input-group">
                <input type="hidden" value="0" name="blogcomments">
                <input type="checkbox" name="blogcomments" id="blogcomments" value="1" <?php if($results['blog']->blogcomments == 1) echo 'checked'?>>
            </div>

So setting the switch to "On" gives the value 1, and if the value is already 1 it will add the checked field, so I'll know what the current state is when editing a blog. Basically I just didn't know about the 'checked' thing. Also, this will return 0 if the box isn't checked. If you don't do this, as the other answer says, it'll return NULL and that doesn't change a 1 to a 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM