Twitter Bootstrap 3 collapse when checkbox checked

前端 未结 8 518
南笙
南笙 2020-12-15 08:43

Accordion have to collapse on checked checkbox. And must be hidden when it\'s uncheked.

Here is code : http://jsfiddle.net/UwL5L/2/

Why it doesn\'t checks? <

相关标签:
8条回答
  • 2020-12-15 09:29

    I know it is an old question but I had some troubles with Firefox and Reloading pages which would leave the checkbox checked and the content hidden - not a good user experience.

    IMO it is the easiest to simply add/remove the class for hiding/showing content depending on the status of the checkbox.

    Here is my example code for this

    
    $(document).ready(function()
    {
        $('input[type=checkbox][data-toggle^=toggle]').on('change',
              function (e) {
                    let checkbox = $(this);
                    let target=$(checkbox.data('target'));
                    if (checkbox.is(":checked")) {
                        target.addClass("show");
                        target.addClass("in");
                    } else {
                        target.removeClass("show");
                        target.removeClass("in");
                    }
                }
        );
        /* Make sure the state is correct - especially after Pressing F5 */
        $('input[type=checkbox][data-toggle^=toggle]').each(
            function (index, elem) {
                    let checkbox = $(this);
                    let target=$(checkbox.data('target'));
                    if (checkbox.is(":checked")) {
                        target.addClass("show");
                        target.addClass("in");
                    } else {
                        target.removeClass("show");
                        target.removeClass("in");
                    }
            }
        )
    });
    

    As you can see you have to simply add the data-toggle=toggle and the data-target element to your input like this:

    <input id="license" type="checkbox" data-toggle="toggle" data-target="#collapseOne"><label for="license">I have Driver License</label>
    

    An example can be found here: https://jsfiddle.net/Kound/z95cLt86/8/

    The code works for bootstrap 3 (.in) and bootstrap 4 (.show). Adopt it to your needs.

    PS: The code also works in combination with https://github.com/gitbrent/bootstrap4-toggle/

    0 讨论(0)
  • 2020-12-15 09:32

    Look at it. I did it and works fine.

    <script> 
            $(function () {
    
                if($('#id_checkbox').prop('checked'))
                {
                    $('#id_collapse').collapse();
                }
            });
    
    </script>
    
    0 讨论(0)
提交回复
热议问题