2 * MediaWiki Widgets - ToggleSwitchWidget class.
4 * @copyright 2017 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
9 * @classdesc Add an invisible checkbox element which will be used to submit the value.
12 * @extends OO.ui.ToggleSwitchWidget
15 * @description Create an instance of `mw.widgets.ToggleSwitchWidget`.
16 * @param {Object} [config] Configuration options
17 * @param {string} [config.name] Name of input to submit results (when used in HTML forms)
19 mw.widgets.ToggleSwitchWidget = function MwWidgetsToggleWidget( config ) {
21 mw.widgets.ToggleSwitchWidget.super.call( this, Object.assign( {}, config, {} ) );
23 if ( 'name' in config ) {
24 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
25 // 'value' and 'defaultValue' properties.
26 this.$hiddenInput = $( '<input>' )
27 .addClass( 'oo-ui-element-hidden' )
28 .attr( 'type', 'checkbox' )
29 .attr( 'name', config.name )
30 .attr( 'id', config.inputId )
31 .appendTo( this.$element );
32 // Update with preset values
33 this.updateHiddenInput();
34 // Set the default value (it might be different from just being empty)
35 this.$hiddenInput.prop( 'defaultChecked', this.isSelected() );
39 // When list of selected tags changes, update hidden input
41 change: 'updateHiddenInput'
47 OO.inheritClass( mw.widgets.ToggleSwitchWidget, OO.ui.ToggleSwitchWidget );
49 mw.widgets.ToggleSwitchWidget.static.tagName = 'span';
53 mw.widgets.ToggleSwitchWidget.prototype.isSelected = function () {
54 return mw.widgets.ToggleSwitchWidget.super.prototype.getValue.call( this );
57 mw.widgets.ToggleSwitchWidget.prototype.getValue = function () {
58 return this.isSelected() ? '1' : '0';
62 * If used inside HTML form, then update hiddenInput.
66 mw.widgets.ToggleSwitchWidget.prototype.updateHiddenInput = function () {
67 if ( '$hiddenInput' in this ) {
68 this.$hiddenInput.prop( 'checked', this.isSelected() );
69 // Trigger a 'change' event as if a user edited the text
70 // (it is not triggered when changing the value from JS code).
71 this.$hiddenInput.trigger( 'change' );