Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / docs / source / Checkbox.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   <title>The source code</title>
6   <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7   <script type="text/javascript" src="../prettify/prettify.js"></script>
8   <style type="text/css">
9     .highlight { display: block; background-color: #ddd; }
10   </style>
11   <script type="text/javascript">
12     function highlight() {
13       document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
14     }
15   </script>
16 </head>
17 <body onload="prettyPrint(); highlight();">
18   <pre class="prettyprint lang-js"><span id='Ext-form-field-Checkbox'>/**
19 </span> * @class Ext.form.field.Checkbox
20  * @extends Ext.form.field.Base
21
22 Single checkbox field. Can be used as a direct replacement for traditional checkbox fields. Also serves as a
23 parent class for {@link Ext.form.field.Radio radio buttons}.
24
25 __Labeling:__ In addition to the {@link Ext.form.Labelable standard field labeling options}, checkboxes
26 may be given an optional {@link #boxLabel} which will be displayed immediately after checkbox. Also see
27 {@link Ext.form.CheckboxGroup} for a convenient method of grouping related checkboxes.
28
29 __Values:__
30 The main value of a checkbox is a boolean, indicating whether or not the checkbox is checked.
31 The following values will check the checkbox:
32 * `true`
33 * `'true'`
34 * `'1'`
35 * `'on'`
36
37 Any other value will uncheck the checkbox.
38
39 In addition to the main boolean value, you may also specify a separate {@link #inputValue}. This will be
40 sent as the parameter value when the form is {@link Ext.form.Basic#submit submitted}. You will want to set
41 this value if you have multiple checkboxes with the same {@link #name}. If not specified, the value `on`
42 will be used.
43 {@img Ext.form.Checkbox/Ext.form.Checkbox.png Ext.form.Checkbox Checkbox component}
44 __Example usage:__
45
46     Ext.create('Ext.form.Panel', {
47         bodyPadding: 10,
48         width      : 300,
49         title      : 'Pizza Order',
50         items: [
51             {
52                 xtype      : 'fieldcontainer',
53                 fieldLabel : 'Toppings',
54                 defaultType: 'checkboxfield',
55                 items: [
56                     {
57                         boxLabel  : 'Anchovies',
58                         name      : 'topping',
59                         inputValue: '1',
60                         id        : 'checkbox1'
61                     }, {
62                         boxLabel  : 'Artichoke Hearts',
63                         name      : 'topping',
64                         inputValue: '2',
65                         checked   : true,
66                         id        : 'checkbox2'
67                     }, {
68                         boxLabel  : 'Bacon',
69                         name      : 'topping',
70                         inputValue: '3',
71                         id        : 'checkbox3'
72                     }
73                 ]
74             }
75         ],
76         bbar: [
77             {
78                 text: 'Select Bacon',
79                 handler: function() {
80                     var checkbox = Ext.getCmp('checkbox3');
81                     checkbox.setValue(true);
82                 }
83             },
84             '-',
85             {
86                 text: 'Select All',
87                 handler: function() {
88                     var checkbox1 = Ext.getCmp('checkbox1'),
89                         checkbox2 = Ext.getCmp('checkbox2'),
90                         checkbox3 = Ext.getCmp('checkbox3');
91
92                     checkbox1.setValue(true);
93                     checkbox2.setValue(true);
94                     checkbox3.setValue(true);
95                 }
96             },
97             {
98                 text: 'Deselect All',
99                 handler: function() {
100                     var checkbox1 = Ext.getCmp('checkbox1'),
101                         checkbox2 = Ext.getCmp('checkbox2'),
102                         checkbox3 = Ext.getCmp('checkbox3');
103
104                     checkbox1.setValue(false);
105                     checkbox2.setValue(false);
106                     checkbox3.setValue(false);
107                 }
108             }
109         ],
110         renderTo: Ext.getBody()
111     });
112
113  * @docauthor Robert Dougan &lt;rob@sencha.com&gt;
114  * @markdown
115  */
116 Ext.define('Ext.form.field.Checkbox', {
117     extend: 'Ext.form.field.Base',
118     alias: ['widget.checkboxfield', 'widget.checkbox'],
119     alternateClassName: 'Ext.form.Checkbox',
120     requires: ['Ext.XTemplate', 'Ext.form.CheckboxManager'],
121
122     fieldSubTpl: [
123         '&lt;tpl if=&quot;boxLabel &amp;&amp; boxLabelAlign == \'before\'&quot;&gt;',
124             '&lt;label class=&quot;{boxLabelCls} {boxLabelCls}-{boxLabelAlign}&quot; for=&quot;{id}&quot;&gt;{boxLabel}&lt;/label&gt;',
125         '&lt;/tpl&gt;',
126         // Creates not an actual checkbox, but a button which is given aria role=&quot;checkbox&quot; and
127         // styled with a custom checkbox image. This allows greater control and consistency in
128         // styling, and using a button allows it to gain focus and handle keyboard nav properly.
129         '&lt;input type=&quot;button&quot; id=&quot;{id}&quot; ',
130             '&lt;tpl if=&quot;tabIdx&quot;&gt;tabIndex=&quot;{tabIdx}&quot; &lt;/tpl&gt;',
131             'class=&quot;{fieldCls} {typeCls}&quot; autocomplete=&quot;off&quot; hidefocus=&quot;true&quot; /&gt;',
132         '&lt;tpl if=&quot;boxLabel &amp;&amp; boxLabelAlign == \'after\'&quot;&gt;',
133             '&lt;label class=&quot;{boxLabelCls} {boxLabelCls}-{boxLabelAlign}&quot; for=&quot;{id}&quot;&gt;{boxLabel}&lt;/label&gt;',
134         '&lt;/tpl&gt;',
135         {
136             disableFormats: true,
137             compiled: true
138         }
139     ],
140
141     isCheckbox: true,
142
143 <span id='Ext-form-field-Checkbox-cfg-focusCls'>    /**
144 </span>     * @cfg {String} focusCls The CSS class to use when the checkbox receives focus
145      * (defaults to &lt;tt&gt;'x-form-cb-focus'&lt;/tt&gt;)
146      */
147     focusCls: Ext.baseCSSPrefix + 'form-cb-focus',
148
149 <span id='Ext-form-field-Checkbox-cfg-fieldCls'>    /**
150 </span>     * @cfg {String} fieldCls The default CSS class for the checkbox (defaults to &lt;tt&gt;'x-form-field'&lt;/tt&gt;)
151      */
152
153 <span id='Ext-form-field-Checkbox-cfg-fieldBodyCls'>    /**
154 </span>     * @cfg {String} fieldBodyCls
155      * An extra CSS class to be applied to the body content element in addition to {@link #fieldBodyCls}.
156      * Defaults to 'x-form-cb-wrap.
157      */
158     fieldBodyCls: Ext.baseCSSPrefix + 'form-cb-wrap',
159
160 <span id='Ext-form-field-Checkbox-cfg-checked'>    /**
161 </span>     * @cfg {Boolean} checked &lt;tt&gt;true&lt;/tt&gt; if the checkbox should render initially checked (defaults to &lt;tt&gt;false&lt;/tt&gt;)
162      */
163     checked: false,
164
165 <span id='Ext-form-field-Checkbox-cfg-checkedCls'>    /**
166 </span>     * @cfg {String} checkedCls The CSS class added to the component's main element when it is in the checked state.
167      */
168     checkedCls: Ext.baseCSSPrefix + 'form-cb-checked',
169
170 <span id='Ext-form-field-Checkbox-cfg-boxLabel'>    /**
171 </span>     * @cfg {String} boxLabel An optional text label that will appear next to the checkbox. Whether it appears before
172      * or after the checkbox is determined by the {@link #boxLabelAlign} config (defaults to after).
173      */
174
175 <span id='Ext-form-field-Checkbox-cfg-boxLabelCls'>    /**
176 </span>     * @cfg {String} boxLabelCls The CSS class to be applied to the {@link #boxLabel} element
177      */
178     boxLabelCls: Ext.baseCSSPrefix + 'form-cb-label',
179
180 <span id='Ext-form-field-Checkbox-cfg-boxLabelAlign'>    /**
181 </span>     * @cfg {String} boxLabelAlign The position relative to the checkbox where the {@link #boxLabel} should
182      * appear. Recognized values are &lt;tt&gt;'before'&lt;/tt&gt; and &lt;tt&gt;'after'&lt;/tt&gt;. Defaults to &lt;tt&gt;'after'&lt;/tt&gt;.
183      */
184     boxLabelAlign: 'after',
185
186 <span id='Ext-form-field-Checkbox-cfg-inputValue'>    /**
187 </span>     * @cfg {String} inputValue The value that should go into the generated input element's value attribute and
188      * should be used as the parameter value when submitting as part of a form. Defaults to &lt;tt&gt;&quot;on&quot;&lt;/tt&gt;.
189      */
190     inputValue: 'on',
191
192 <span id='Ext-form-field-Checkbox-cfg-uncheckedValue'>    /**
193 </span>     * @cfg {String} uncheckedValue If configured, this will be submitted as the checkbox's value during form
194      * submit if the checkbox is unchecked. By default this is undefined, which results in nothing being
195      * submitted for the checkbox field when the form is submitted (the default behavior of HTML checkboxes).
196      */
197
198 <span id='Ext-form-field-Checkbox-cfg-handler'>    /**
199 </span>     * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
200      * handling the {@link #change change event}). The handler is passed the following parameters:
201      * &lt;div class=&quot;mdetail-params&quot;&gt;&lt;ul&gt;
202      * &lt;li&gt;&lt;b&gt;checkbox&lt;/b&gt; : Ext.form.field.Checkbox&lt;div class=&quot;sub-desc&quot;&gt;The Checkbox being toggled.&lt;/div&gt;&lt;/li&gt;
203      * &lt;li&gt;&lt;b&gt;checked&lt;/b&gt; : Boolean&lt;div class=&quot;sub-desc&quot;&gt;The new checked state of the checkbox.&lt;/div&gt;&lt;/li&gt;
204      * &lt;/ul&gt;&lt;/div&gt;
205      */
206
207 <span id='Ext-form-field-Checkbox-cfg-scope'>    /**
208 </span>     * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
209      * (defaults to this Checkbox).
210      */
211
212     // private overrides
213     checkChangeEvents: [],
214     inputType: 'checkbox',
215     ariaRole: 'checkbox',
216
217     // private
218     onRe: /^on$/i,
219
220     initComponent: function(){
221         this.callParent(arguments);
222         this.getManager().add(this);
223     },
224
225     initValue: function() {
226         var me = this,
227             checked = !!me.checked;
228
229 <span id='Ext-form-field-Checkbox-property-originalValue'>        /**
230 </span>         * The original value of the field as configured in the {@link #checked} configuration, or
231          * as loaded by the last form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad}
232          * setting is &lt;code&gt;true&lt;/code&gt;.
233          * @type Mixed
234          * @property originalValue
235          */
236         me.originalValue = me.lastValue = checked;
237
238         // Set the initial checked state
239         me.setValue(checked);
240     },
241
242     // private
243     onRender : function(ct, position) {
244         var me = this;
245         Ext.applyIf(me.renderSelectors, {
246 <span id='Ext-form-field-Checkbox-property-boxLabelEl'>            /**
247 </span>             * @property boxLabelEl
248              * @type Ext.core.Element
249              * A reference to the label element created for the {@link #boxLabel}. Only present if the
250              * component has been rendered and has a boxLabel configured.
251              */
252             boxLabelEl: 'label.' + me.boxLabelCls
253         });
254         Ext.applyIf(me.subTplData, {
255             boxLabel: me.boxLabel,
256             boxLabelCls: me.boxLabelCls,
257             boxLabelAlign: me.boxLabelAlign
258         });
259
260         me.callParent(arguments);
261     },
262
263     initEvents: function() {
264         var me = this;
265         me.callParent();
266         me.mon(me.inputEl, 'click', me.onBoxClick, me);
267     },
268
269 <span id='Ext-form-field-Checkbox-method-onBoxClick'>    /**
270 </span>     * @private Handle click on the checkbox button
271      */
272     onBoxClick: function(e) {
273         var me = this;
274         if (!me.disabled &amp;&amp; !me.readOnly) {
275             this.setValue(!this.checked);
276         }
277     },
278
279 <span id='Ext-form-field-Checkbox-method-getRawValue'>    /**
280 </span>     * Returns the checked state of the checkbox.
281      * @return {Boolean} True if checked, else false
282      */
283     getRawValue: function() {
284         return this.checked;
285     },
286
287 <span id='Ext-form-field-Checkbox-method-getValue'>    /**
288 </span>     * Returns the checked state of the checkbox.
289      * @return {Boolean} True if checked, else false
290      */
291     getValue: function() {
292         return this.checked;
293     },
294
295 <span id='Ext-form-field-Checkbox-method-getSubmitValue'>    /**
296 </span>     * Returns the submit value for the checkbox which can be used when submitting forms.
297      * @return {Boolean/null} True if checked; otherwise either the {@link #uncheckedValue} or null.
298      */
299     getSubmitValue: function() {
300         var unchecked = this.uncheckedValue,
301             uncheckedVal = Ext.isDefined(unchecked) ? unchecked : null;
302         return this.checked ? this.inputValue : uncheckedVal;
303     },
304
305 <span id='Ext-form-field-Checkbox-method-setRawValue'>    /**
306 </span>     * Sets the checked state of the checkbox.
307      * @param {Boolean/String} value The following values will check the checkbox:
308      * &lt;code&gt;true, 'true', '1', or 'on'&lt;/code&gt;, as well as a String that matches the {@link #inputValue}.
309      * Any other value will uncheck the checkbox.
310      * @return {Boolean} the new checked state of the checkbox
311      */
312     setRawValue: function(value) {
313         var me = this,
314             inputEl = me.inputEl,
315             inputValue = me.inputValue,
316             checked = (value === true || value === 'true' || value === '1' ||
317                       ((Ext.isString(value) &amp;&amp; inputValue) ? value == inputValue : me.onRe.test(value)));
318
319         if (inputEl) {
320             inputEl.dom.setAttribute('aria-checked', checked);
321             me[checked ? 'addCls' : 'removeCls'](me.checkedCls);
322         }
323
324         me.checked = me.rawValue = checked;
325         return checked;
326     },
327
328 <span id='Ext-form-field-Checkbox-method-setValue'>    /**
329 </span>     * Sets the checked state of the checkbox, and invokes change detection.
330      * @param {Boolean/String} checked The following values will check the checkbox:
331      * &lt;code&gt;true, 'true', '1', or 'on'&lt;/code&gt;, as well as a String that matches the {@link #inputValue}.
332      * Any other value will uncheck the checkbox.
333      * @return {Ext.form.field.Checkbox} this
334      */
335     setValue: function(checked) {
336         var me = this;
337
338         // If an array of strings is passed, find all checkboxes in the group with the same name as this
339         // one and check all those whose inputValue is in the array, unchecking all the others. This is to
340         // facilitate setting values from Ext.form.Basic#setValues, but is not publicly documented as we
341         // don't want users depending on this behavior.
342         if (Ext.isArray(checked)) {
343             me.getManager().getByName(me.name).each(function(cb) {
344                 cb.setValue(Ext.Array.contains(checked, cb.inputValue));
345             });
346         } else {
347             me.callParent(arguments);
348         }
349
350         return me;
351     },
352
353     // private
354     valueToRaw: function(value) {
355         // No extra conversion for checkboxes
356         return value;
357     },
358
359 <span id='Ext-form-field-Checkbox-method-onChange'>    /**
360 </span>     * @private
361      * Called when the checkbox's checked state changes. Invokes the {@link #handler} callback
362      * function if specified.
363      */
364     onChange: function(newVal, oldVal) {
365         var me = this,
366             handler = me.handler;
367         if (handler) {
368             handler.call(me.scope || me, me, newVal);
369         }
370         me.callParent(arguments);
371     },
372
373     // inherit docs
374     getManager: function() {
375         return Ext.form.CheckboxManager;
376     },
377
378     onEnable: function() {
379         var me = this,
380             inputEl = me.inputEl;
381         me.callParent();
382         if (inputEl) {
383             // Can still be disabled if the field is readOnly
384             inputEl.dom.disabled = me.readOnly;
385         }
386     },
387
388     setReadOnly: function(readOnly) {
389         var me = this,
390             inputEl = me.inputEl;
391         if (inputEl) {
392             // Set the button to disabled when readonly
393             inputEl.dom.disabled = readOnly || me.disabled;
394         }
395         me.readOnly = readOnly;
396     },
397
398 <span id='Ext-form-field-Checkbox-method-getBodyNaturalWidth'>    /**
399 </span>     * @protected Calculate and return the natural width of the bodyEl. It's possible that the initial
400      * rendering will cause the boxLabel to wrap and give us a bad width, so we must prevent wrapping
401      * while measuring.
402      */
403     getBodyNaturalWidth: function() {
404         var me = this,
405             bodyEl = me.bodyEl,
406             ws = 'white-space',
407             width;
408         bodyEl.setStyle(ws, 'nowrap');
409         width = bodyEl.getWidth();
410         bodyEl.setStyle(ws, '');
411         return width;
412     }
413
414 });
415 </pre>
416 </body>
417 </html>