用个简单的文本框:
1, 定义 Form
var myForm = new Ext.form.FormPanel({
renderTo: Ext.getBody(),
title: "Form Demo -- Get Field Value",
//width: 500, // define the width of form, work well,
// but when using style config, 'px' can not be omitted!!! This rule also applies to 'margin', 'padding' ...
style: "width: 500px; margin: 10px;",
bodyStyle: "padding: 10px;",
frame: true,
labelAlign: "right", //can only work in v3.x
buttonAlign: "center",
items:[
{
xtype: "textfield",
id: "txtName",
name: "myName",
fieldLabel: "Name"
}
]
});
2, TextField 配置了 id 属性, 可以直接获取到这个组件:
alert("Cmp Value: " + Ext.getCmp("txtName").getValue());
PS :文档说明:
[ All Components are registered with the Ext.ComponentMgr on construction so that they can be referenced at any time via Ext.getCmp, passing the id. ]
3, 既然用到了表单, 也可以利用 findField() 方法来得到文本框组件,参数就可以利用到 id 和 name 了。
参数说明: [ The value to search for (specify either a id, dataIndex, name or hiddenName). ]
但首先还要获得 Form 的引用, getForm() 即可:
// get current form object
var thisForm = myForm.getForm();
// show the value of text via various methods -- same result
alert("ID: " + thisForm.findField("txtName").getValue());
alert("Name: " + thisForm.findField("myName").getValue());
alert("DataIndex: " + thisForm.findField(0).getValue());
PS: 可以验证下 findField & getCmp 是获取了文本框的同一个引用:
//- true , here attention: convert bool value to string is essential, but do not know the reason ?
alert("Field Equal: " + (thisForm.findField("txtName") === Ext.getCmp("txtName")).toString());
还可以一次性获取所有的表单元素:
// or get all the values once - default json type: key(name):value , so sometimes the name attr is needed
// Ext.encode() -- to show the json reslut, or 'JSON.stringify()'
alert("All Values: " + Ext.encode(thisForm.getValues()));
OK....