ons-switch

Switch component. The switch can be toggled both by dragging and tapping. Will automatically displays a Material Design switch on Android devices.

Tutorial

Switches

A switch is an UI element that can be used to toggle between two states.

The state of a switch in Onsen UI can be changed both by dragging the knob and by tapping on the switch.

To make the switch enabled by default you can use the checked attribute just like with radio buttons and checkboxes.

<ons-switch checked>
</ons-switch>

To disable the switch the disabled attribute is used.

<ons-switch disabled>
</ons-switch>

Getting the value

To get the value of an <ons-switch> element you need to get a reference to the DOM element and read the checked property.

var switch = document.getElementById('switch-1');
ons.notification.alert('Value is ' + switch.checked);

See also

Attributes

Attributes are added directly to the element. You can do this in HTML or JS.

HTML: <ons-switch someAttribute="true" anotherAttribute><ons-switch>
JS: document.querySelector('ons-switch').setAttribute('someAttribute', 'true')

Name Type Description
modifier String The appearance of the switch. Optional.
disabled Whether the switch is be disabled. Optional.
checked Whether the switch is checked. Optional.
input-id String Specify the id attribute of the inner <input> element. This is useful when using <label for="..."> elements. Optional.

Properties

Properties are accessed on the element through JS, and should be get and set directly. For example: document.querySelector('ons-switch').checked.

Name Description
checked This value is true if the switch is checked.
value The current value of the input.
disabled Whether the element is disabled or not.
checkbox The underlying checkbox element.

Preset Modifiers

Modifiers are set in the modifier attribute. To use more than one, separate them by spaces. For example:
<ons-switch modifier="material modifier2"><ons-switch>.

Name Description
material Material Design switch

Events

To use these events, add event listeners to the elements as you would for native events, like click. For example: document.querySelector('ons-switch').addEventListener('change', function() { ... }).

Name Description
change Fired when the switch is toggled.
change

Fired when the switch is toggled.

Parameters
Name Type Description
event Object Event object.
event.switch Object Switch object.
event.value Boolean Current value.
event.isInteractive Boolean True if the change was triggered by the user clicking on the switch.

Need Help?

If you have any questions, use our Community Forum or talk to us on Discord chat. The Onsen UI team and your peers in the community will work together to help solve your issues.

For bug reports and feature requests use our GitHub Issues page.