The situation:
You have a form with a single input box and an ajax submit link or button, much like the main search box on google or zoomf.
The problem:
If you type in the input box and press return the form gets submitted automatically. Firefox does this by simulating a click on the first button it finds in the form, which is OK. IE does this by just submitting the form, which is bad as it ruins the functionality of your form. If you have an AjaxSubmitLink rather than button even Firefox cant get it right.
The solution:
Use prototype to intercept the submit event of the form, stop the event, and fire the onclick event of your ajax button/link.
$('formId').observe('submit', function(e){ Event.stop(e); $('submitId').onclick(null);});
A wicketifed solution:
Wrap this up in a wicket behaviour so it can be resued.
import org.apache.wicket.Component;
import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.markup.html.IHeaderResponse;
public class StopFormSubmitBehaviour extends AbstractBehavior {
private Component submitButton;
private Component form;
public StopFormSubmitBehaviour(Component submitButton)
{
this.submitButton = submitButton;
submitButton.setOutputMarkupId(true);
}
@Override
public void bind(Component component) {
super.bind(component);
component.setOutputMarkupId(true);
this.form = component;
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.renderOnDomReadyJavascript(getScript());
}
protected String getScript()
{
StringBuilder js = new StringBuilder();
js.append("$('").append(form.getMarkupId()).append("').observe('submit', function(e){
Event.stop(e); $('")
.append(submitButton.getMarkupId()).append("').onclick(null);});");
return js.toString();
}
}
In action:
Form form = new Form("f");
form.add(new TextField("i"));
AjaxSubmitLink b;
form.add(b = new AjaxSubmitLink("b"){
@Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
}
});
add(form);
form.add(new StopFormSubmitBehaviour(b));
Tags:
ajax,
form,
prototype,
Wicket