Search code examples
jqueryrazorslidetoggle

Set Toggle switch based on condition on page load


Here is my code -

(function () {
        $(document).ready(function () {
            
            $('.switch-input').on('change', function () {
                var isChecked = $(this).is(':checked');
                var selectedData;
                var $switchLabel = $('.switch-label');
                if (isChecked) {
                    selectedData = $switchLabel.attr('data-on');
                } else {
                    selectedData = $switchLabel.attr('data-off');
                }
                if (selectedData === 'ACTIVE') {
                    selectedData = 'A';
                } else {
                    selectedData = 'C';
                }
                $('#h-status').val(selectedData);
                $('#form_filterBillItems').submit();
            });
        });

    })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
                        <input class="switch-input" type="checkbox"/>
                        <span id ="tglInp" class="switch-label" data-on="CANCEL" data-off="ACTIVE"></span> <span class="switch-handle"></span>
                    </label>

I have this toggle switch that displays a filtered list based on the switch value : 'ACTIVE' or 'CANCEL'

This is on a Razor view. The grid that displays the list is in a partial view. But the toggle switch is on the full view.

The issue is when I return to this view, the grid is filtered based on the condition but the switch goes back to its default state. For example, if I go to the next view from Toggle switch state Cancel, when I return it should be still on Cancel but the toggle switch is on Active.

How do I do that. Any help would be highly appreciated! This is my first question, so if I made any mistakes, in posting, I apologize.

Thank you!


Solution

  • I added another javascript function to check for the toggle switch value and change it based on the condition.

    Here is my updated code -

    $(document).ready(function () {
                var data = @Html.Raw(Json.Encode(ViewData["bi_status"]));
                if (data==='A'){ data = 'ACTIVE'; } else{ data = 'CANCEL'; }
               $('.switch-input').on('change', function () {...});
            });
        })();
        
    
        function setSwitch(args) {
            var $switchLabel = $('.switch-label');
            var $switchInput = document.getElementById('tglInp');
            var dataOn = $switchLabel.attr('data-on');
            var dataOff = $switchLabel.attr('data-off');
            if (args === 'CANCEL') {
                $switchInput.checked = true;
                $switchLabel.attr('data-on', dataOn);
    
            } else {
                $switchInput.checked = false;
                $switchLabel.attr('data-off', dataOff);
            }
        }

    -- For anyone looking for an answer to a similar issue. Cheers!