tags:

views:

3296

answers:

6

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?

A: 

Try the "buttonDown" event; it may be dispatched in either case. Otherwise you are probably looking at using "keyDown" and checking the key that was pressed.

cliff.meyers
A: 

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.

Jason Maskell
what if the form has more than one button? Which gets bound to Enter?
Herms
See the defaultButton attribute of the form element. Nonetheless, this is definitely not the solution that the question poster has been looking for.
David Hanak
+3  A: 

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!

Christian Nunciato
A: 

Even better

 private function setValidationFocus(formObject:Object):void
 {
  formObject.setFocus();
  formObject.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));  // sneaky sneaky
  formObject.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));
 }
+1  A: 

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()"/>

A: 

I've been lookind at the same problem but the answer from Christian Nunciato seem's to me to be the best. One more thing to add to his solution, I think that the bubbling, flag in btn.dispatchEvent(new MouseEvent(MouseEvent.CLICK)), should be set to false (btn.dispatchEvent(new MouseEvent(MouseEvent.CLICK, false))) because the event should be isolated on the button.

George