表單定義
var fp = Ext.create('Ext.form.Panel', {
frame: true,
fieldDefaults: { labelWidth: 110 },
width: 500,
bodyPadding: 10,
items: [{
xtype: 'fieldset',
flex: 1,
defaultType: 'checkbox',
layout: 'anchor',
defaults: { anchor: '100%', hideEmptyLabel: false },
items: [{
fieldLabel: '請選擇拒絕原因:',
boxLabel: '該表沒有填寫完整。',
name: 'integrity',
inputValue: '1'
}, {
name: 'correct',
boxLabel: '該表填寫不准確。',
inputValue: '1'
}]
}],
buttons: [{
text: '確認',
handler: function() {
var form = fp.getForm();
if (form.isValid()) {
// 關鍵:findField 取得欄位元件,getValue 取得布林值
var integrity = form.findField('integrity').getValue() ? 1 : 0;
var correct = form.findField('correct').getValue() ? 1 : 0;
console.log('完整性:', integrity, '準確性:', correct);
// 提交邏輯...
}
}
}, {
text: '取消',
handler: function() { fp.up('window').hide(); }
}]
});
關鍵 API
| 方法 | 說明 |
form.findField(name) | 依 name 遞迴查找欄位元件 |
field.getValue() | Checkbox 回傳 true/false(勾選狀態) |
field.getSubmitValue() | 回傳提交給後端的值(inputValue 或 undefined) |
field.setValue(v) | 程式化設定勾選狀態 |
常見坑點
- 不要用
form.getValues() 直接取 Checkbox:未勾選時不會包含在提交資料中,導致無法區分「未勾選」vs「欄位不存在」。
inputValue 僅影響表單提交時的值,getValue() 永遠回傳布林。
- 若需取得「勾選時的值」,用
field.getSubmitValue()。
批次取得多個 Checkbox 值
var values = {};
form.getFields().filterBy(function(f) { return f.isXType('checkbox'); }).each(function(f) {
values[f.name] = f.getValue() ? 1 : 0;
});
console.log(values); // { integrity: 1, correct: 0 }