Search code examples
javascriptjquerybootstrap-4bootstrap-5

Disabling inputs in Bootstrap based on toggle switch selection?


Reading through the documentation, I'm trying to find a way in bootstrap 5 to disable other input fields if a toggle switch input is set to 'off'?

Parent element is #member_form, switch is 'toggleswitch'.

The following will disable the field when anything is the form is clicked. But I'd like to switch from enabled to disabled and back based on the the toggleswitch element?

    $(document).on('click', '#member_form', function(){
        $("#input_name").attr('disabled','disabled');
    });

Any suggestions?


Solution

  • In Bootstrap 5, you can use Bootstrap Switch for toggling and JavaScript to disable other input fields based on the toggle state.

    $(document).ready(function(){
        $('#toggle_switch').bootstrapToggle({
            on: 'Enabled',
            off: 'Disabled'
        });
    
        $('#toggle_switch').change(function(){
            if($(this).prop('checked')){
                $("#input_name").prop('disabled', false);
                // Enable other input fields if needed
            } else {
                $("#input_name").prop('disabled', true);
                // Disable other input fields if needed
            }
        });
    });
        <div class="mb-3">
            <label for="toggle_switch" class="form-label">Toggle</label>
            <input type="checkbox" id="toggle_switch" data-toggle="toggle">
        </div>
        <div class="mb-3">
            <label for="input_name" class="form-label">Name</label>
            <input type="text" class="form-control" id="input_name">
        </div>