What's the best way to cause a Flex 3 button to respond to the enter key?
Solution 1
Sure, you could do something like this:
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function btn_click(event:MouseEvent):void
{
Alert.show("Clicked!");
}
private function btn_keyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.ENTER)
btn.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}
]]>
</mx:Script>
<mx:Button id="btn" label="Click Me" click="btn_click(event)" keyDown="btn_keyDown(event)" />
... although I'm not a huge fan of dispatching events on objects outside of those objects. A cleaner approach might be to subclass Button, add the listeners and handlers inside your subclass, and then dispatch the click event from within that class. But this should help illustrate the point. Good luck!
Solution 2
For something like a login form, you need to actually use an mx:form - here's the code snippet that illustrates it:
<mx:Form defaultButton="{loadButton}">
<mx:TextInput id="feedURL" />
<mx:Button id="loadButton" label="Load" click="someHandler(event)" />
</mx:Form>
Enter the url and hit enter, bam, expected behavior.
Googled from here.
Solution 3
If you are submitting a form like a Login dialog or the like, the "enter" property on the TextField is a great solution:
<mx:TextInput displayAsPassword="true" id="wPassword" enter="handleLoginSubmit()"/>
Solution 4
You can also add the KEY_DOWN
listener in Christian's answer to the button itself. Just make sure you call stopImmediatePropagation. In this example I let any key cause the button action. And I am using the same handler so I allow any "Event" type. You could use different "cancelClick" handlers.
protected function cancelClick(e:Event = null):void{
this.dispatchEvent(new Event(Event.CANCEL)); // do component action
e.stopImmediatePropagation();
}
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName,instance);
switch(instance){
case cancel:
cancel.addEventListener(MouseEvent.CLICK,cancelClick);
cancel.addEventListener(KeyboardEvent.KEY_DOWN,cancelClick);
}
}
Related videos on Youtube
Jim In Texas
Updated on April 21, 2022Comments
-
Jim In Texas about 2 years
In Flex 3, buttons call their click handler when they are clicked on by the mouse, or when they have the focus and the user depresses the space bar.
Is there a straightforward way to cause Flex 3 buttons with focus to call their click handler when the user presses the enter key?
-
MarioRicalde over 15 yearswhat if the form has more than one button? Which gets bound to Enter?
-
David Hanak over 15 yearsSee the defaultButton attribute of the form element. Nonetheless, this is definitely not the solution that the question poster has been looking for.