JavaScript/jQuery Switch - Getting Started
The Switch component allows users to switch between ON (the value is true
) and OFF (the value is false
) states.
This tutorial shows how to add Switch to a page and configure its core features. The following sample shows the customization result:
Each section in this tutorial describes a single configuration step. You can also find the full source code in the following GitHub repository: getting-started-with-switch.
Create a Switch
Add DevExtreme to your jQuery application and use the following code to create a Switch component:
- $(function() {
- $("#switch").dxSwitch({ });
- });
- <html>
- <head>
- <!-- ... -->
- <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
- <link rel="stylesheet" href="https://cdn3.devexpress.com/jslib/24.2.3/css/dx.light.css">
- <script type="text/javascript" src="https://cdn3.devexpress.com/jslib/24.2.3/js/dx.all.js"></script>
- <script type="text/javascript" src="index.js"></script>
- </head>
- <body>
- <div id="switch"></div>
- </body>
- </html>
Specify the Initial State
If you need to specify the initial state, assign a Boolean value to the value property. You can also change the Switch component labels. Use the switchedOnText and the switchedOffText properties.
- $(function() {
- $("#switch").dxSwitch({
- value: false,
- });
- });
Configure Size
The component allows you to change its width.
You can also use rtlEnabled property to enable the Right-to-Left layout.
- $(function() {
- $("#switch").dxSwitch({
- // ...
- width: 80,
- rtlEnabled: true,
- });
- });
Define a Hint
The following code specifies the hint that appears when users hover the mouse pointer over the Switch.
- $(function() {
- $("#switch").dxSwitch({
- // ...
- hint: "Click to switch on",
- onValueChanged(e) {
- const messageText= e.value ? "Click to switch off" : "Click to switch on";
- e.component.option("hint", messageText);
- // ...
- }
- });
- });
Handle Value Change
Users can change a component value (state) with a mouse click, SPACE key, or tap. Implement the onValueChanged callback to handle value changes.
The following code displays a notification every time users change the Switch state:
- $(function() {
- $("#switch").dxSwitch({
- // ...
- onValueChanged(e) {
- // ...
- const stateLabel = e.value ? "ON" : "OFF";
- DevExpress.ui.notify(`The component is switched ${stateLabel}`);
- }
- });
- });
If you have technical questions, please create a support ticket in the DevExpress Support Center.