Search code examples
jquerytwitter-bootstrapbootstrap-switch

bootstrap-switch: Disable/Enable other options on change


I use bootstrap-switch and have different buttons. Given a change, I want to give other attributes as parameters like in this sample:

<input type="checkbox" name="values[{$optionName}]" value="1" data-to-enable="values[optionName1],values[optionName5],values[optionName50],values[optionName100],values[optionName333]" />

I want these options to be disabled on unchecked (or when it's unchecked on page load), and enabled (or when it's checked on page load) on checked.


Solution

  • Here is the javascript code you want:

    $(function() {
    
        var toggleSwitch = function(ev) {
            var _this = $(ev.currentTarget);
            var toChange = _this.data("to-enable").split(",");
            var state = _this.bootstrapSwitch("state");
    
            $("input.switch").each(function(el, index) {
                if($.inArray($(this).prop("name"), toChange) >= 0) {
                    $(this).bootstrapSwitch("disabled", state);
                }
            });
        }       
    
        $("input").bootstrapSwitch();
        $("input[id^='switchHandler']").each(function(){
            $(this).bootstrapSwitch("state", $(this).data("checked"));
            $(this).on("switchChange.bootstrapSwitch", toggleSwitch);
            $(this).trigger("switchChange.bootstrapSwitch");
        });
    
    });
    

    And here is a working jsfiddle