tags:

views:

484

answers:

2

How do you set focus on a component with Apache Wicket? Searching leads to very little information, mostly on setting the default field. I do not want to set a default field, rather I am looking to set focus when, for example, a specific radio button is selected.

+4  A: 

Once you create your behavior to set the focus, you should be able to add it to the component on any event, just make sure that component is part of the AjaxRequestTarget. I don't see why this wouldn't work...

myRadioButton.add(new AjaxEventBehavior("onchange") {
 @Override
 protected void onEvent(AjaxRequestTarget target) {
    myOtherComponent.add(new DefaultFocusBehavior());
        target.addComponent(myForm);
 }
});

Here's a link that shows how to create the default focus behavior if you do not have one already: http://javathoughts.capesugarbird.com/2009/01/wicket-and-default-focus-behavior.html

schmimd04
+1  A: 

If you only want to setFocus through javascript and don't want to reload a form or a component, you can use the following code:

import org.apache.wicket.Component;

public class JavascriptUtils {
    private JavascriptUtils() {

    }

    public static String getFocusScript(Component component) {
        return "document.getElementById('" + component.getMarkupId() + "').focus();";
    }
}

And then in any Ajax Method you can use:

target.appendJavascript(JavascriptUtils.getFocusScript(componentToFocus));
Marcelo Hernández Rishmawy