複選框(CheckBox)主要用來接收使用者的勾選,那麼在 Extjs 4.x 中,該如何取得 Form 裡複選框的值呢?本文示範一個實用的彈窗範例,示範如何讀取勾選結果。
我們先建立一個彈窗作為載體,其 items 中的 [fp] 就是表單的句柄:
var win = new Ext.Window({
modal: true,
title: '確定要拒絕該表嗎?',
width: 500,
plain: true,
items: [fp]
});
win.show();
接著定義表單 fp,其中用 fieldset 搭配 defaultType: 'checkbox' 來建立多個複選框:
var fp = Ext.create('Ext.FormPanel', {
frame: true,
fieldDefaults: { labelWidth: 110 },
width: 500,
bodyPadding: 10,
items: [{
xtype: 'fieldset',
flex: 1,
defaultType: 'checkbox',
layout: 'anchor',
items: [{
fieldLabel: '請選擇拒絕原因:',
boxLabel: '該表沒有填寫完整。',
name: 'integrity',
inputValue: '1'
}, {
name: 'correct',
boxLabel: '該表填寫不准確。',
inputValue: '1'
}]
}],
buttons: [{
text: '確認',
handler: function() {
if (fp.getForm().isValid()) {
console.log(fp.getForm().findField('integrity').getValue() ? 1 : 0);
console.log(fp.getForm().findField('correct').getValue() ? 1 : 0);
}\br /> win.hide();\br /> }
}]
});
真正的重點在這兩行——透過 findField 找到欄位後呼叫 getValue(),再用三元運算子把布林值轉成 1 或 0:
console.log(fp.getForm().findField('integrity').getValue() ? 1 : 0);
console.log(fp.getForm().findField('correct').getValue() ? 1 : 0);
這樣就能取得「完整性」與「正確性」兩個選項的勾選狀態。整個範例涵蓋了彈窗、表單、fieldset 與按鈕等常用元素,實際操作並不難,細節可再參考官方 API。