Rox
Rox

Reputation: 2917

How add a onClick method to a TextField (ExtJS Framework)?

I would like to know how to add an onClick() method to a Ext.form.Text component.

If the component is a button, then all I have to do is to add this line:

handler: function() {alert("Hello!");}

But that line doesn´t work if the component is a textfield. Look at the example below:

Ext.create('Ext.form.Panel', {
    title: 'Contact Info',
    width: 300,
    bodyPadding: 10,
    renderTo: Ext.getBody(),
    items: [{
        id: 'myButton',
        xtype: 'textfield',
        name: 'name',
        fieldLabel: 'Name',
        style: 'background-color: #ddd;',
        allowBlank: false,
        handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Does not work!
    }, {
        xtype: 'button',
        name: 'email',
        fieldLabel: 'Email Address',
        style: 'background-color: green',
        textfieldStyle: 'background-color: green',
        handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Works!

    }]
});

Upvotes: 3

Views: 21643

Answers (2)

Krzysztof
Krzysztof

Reputation: 16130

Handler is a shortcut for the default action listener. For a button this is obviously click, but a text field doesn't have a default action. In addition, a text field does not actually fire a click event, but you can always add an event handler to the dom element:

Ext.create('Ext.form.Panel', {
    title: 'Contact Info',
    width: 300,
    bodyPadding: 10,
    renderTo: Ext.getBody(),
    items: [{
        id: 'myButton',
        xtype: 'textfield',
        name: 'name',
        fieldLabel: 'Name',
        style: 'background-color: #ddd;',
        allowBlank: false,
        listeners: {
            render: function() {
                this.getEl().on('mousedown', function(e, t, eOpts) {
                    Ext.getCmp('myButton').setValue("TEXT")
                });
            }
        }
    }]
});

Upvotes: 12

KBIIX
KBIIX

Reputation: 911

Ext.create('Ext.form.Panel', {
    title: 'Contact Info',
    width: 300,
    bodyPadding: 10,
    renderTo: Ext.getBody(),
    items: [{
        id: 'myButton',
        xtype: 'textfield',
        name: 'name',
        fieldLabel: 'Name',
        style: 'background-color: #ddd;',
        allowBlank: false,
        listeners: {
            render: function( component ) {
                component.getEl().on('click', function( event, el ) {
                    component.setValue("TEXT");
                });
            }
        }
    }, {
        xtype: 'button',
        name: 'email',
        fieldLabel: 'Email Address',
        style: 'background-color: green',
        textfieldStyle: 'background-color: green',
        handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Works!

    }]
});

Upvotes: 3

Related Questions