Prevent State Change in EJ2 JavaScript Switch control

14 Dec 20243 minutes to read

The beforeChange event is triggered before the switch’s state is altered. This event provides an opportunity to intercept and potentially cancel the change action before it is applied. It allows for implementing conditional logic or validating the change prior to it being rendered on the UI.

ej.base.enableRipple(true);

// Initialize Switch component.
var switchObj = new ej.buttons.Switch({ checked: true, beforeChange: beforeChange });

// Render initialized Switch.
switchObj.appendTo('#element');

function beforeChange(args) {
    // Set cancel to true to prevent the switch state change
    args.cancel = true;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Switch</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Typescript UI Controls">
    <meta name="author" content="Syncfusion">
    <link href="https://cdn.syncfusion.com/ej2/31.2.12/ej2-base/styles/fabric.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/31.2.12/ej2-buttons/styles/material.css" rel="stylesheet">
    <link href="styles.css" rel="stylesheet">
    <script src="https://cdn.syncfusion.com/ej2/31.2.12/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id="container">
        <input type="checkbox" id="element">
    </div>

    <script>
        var ele = document.getElementById('container');
        if (ele) {
            ele.style.visibility = "visible";
        }   
    </script>
    <script src="index.js" type="text/javascript"></script>
</body>

</html>
#container {
    visibility: hidden;
    margin-left: 10px;
}

#loader {
  color: #008cff;
  height: 40px;
  width: 30%;
  position: absolute;
  top: 45%;
  left: 45%;
}

.e-switch-wrapper {
  margin-top: 18px;
}