简体   繁体   中英

How can I check if Shift+Enter is pressed on a textarea

I want to submit the form if Enter is pressed and stop the event if Shift + Enter is pressed. The callback for this has Ext.EventObject parameter which does not provide any way to check if shiftkey is pressed.

it has two methods .hasModifier and .isSpecialKey . Both returns boolean . There is no way to find if shiftkey is pressed. how do I trace it?

This is my textarea component:

{
    region : 'center',
    margins : '5 0 0 0',
    xtype : 'textarea',
    name : 'chatmessage',
    enableKeyEvents: true,
    listeners: {
        keydown: function(textfield, evt, eOpts){
            console.log(evt.getKey());
        }
    }
}

I tried evt.shiftKey . Its undefined.

This can be done with little trick with keydown and keyup events a flag.

listeners : {
    keydown : function(tf, e, opt) {
        if (e.getKey() == e.SHIFT) {
            this.shiftKeyPressed = true; // a flag
            return;
        }
        if (e.getKey() != e.ENTER && (this.shiftKeyPressed == undefined || (this.shiftKeyPressed == false))) {
            // Submit form
            e.stopEvent();
        }
    },
    keyup : function(tf, e, eOpts) {
        if (e.getKey() == e.SHIFT) {
            this.shiftKeyPressed = false;
        }
    }
}

Why dont you use a keymap ( http://docs.sencha.com/ext-js/4-1/#!/api/Ext.util.KeyMap ) on your textarea? Can't test the code here but should be something like this:

var textArea= Ext.create('Ext.form.field.TextArea', {
    region : 'center',
    margins : '5 0 0 0',
    xtype : 'textarea',
    name : 'chatmessage',
    enableKeyEvents: true
});

var map = new Ext.util.KeyMap({
    target: textArea,
    binding: [{
        key: Ext.EventObject.ENTER,
        fn: function(){ alert('Enter pressed!'); }
    }, {
        key: Ext.EventObject.ENTER,
        shift:true,
        fn: function(){ alert('Shift+ENTER pressed!'); }
    }]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM