MrMime MrMime - 5 months ago 51
Ajax Question

Wicket - AjaxFormComponentUpdatingBehavior and backspace

I have a

TextField
where I have added an
AjaxFormComponentUpdatingBehavior
to get the current value when user write some string.

filterByObject = new TextField<String>("filterByObject", true, new PropertyModel<String>(searchParams, "objectFilter"));
AjaxFormComponentUpdatingBehavior changeFilterBinded = new AjaxFormComponentUpdatingBehavior ("onkeyup") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
target.addComponent(componentToUpdate);
}
};
filterByObject.add(changeFilterBinded);


When I put some chars inside
textfield
,
onUpdate
method is correctly called and my component, based on the current state of
searchParams
, changes correctly.
Unfortunally when I use Backspace to cancel what I have inserted, the
onUpdate
is not called.

I tried changing event (
onkeypress
,
onkeydown
,
onchange
etc...) but it doesn't work. Only
onChange
works but I have to change focus to another component.

How can I save the day?

Answer

Is the input in the field invalid (according to setRequired or IValidators added to the field) as a result of pressing the backspace key? If it is, the onError method will be called instead of onUpdate, because user input will be invalid and therefore will not reach the ModelObject of the component with the AjaxFormComponentUpdatingBehavior.

AjaxFormComponentUpdatingBehavior  changeFilterBinded = 
  new AjaxFormComponentUpdatingBehavior ("onkeyup") {
    @Override
    protected void onUpdate(AjaxRequestTarget target) {     
        // Here the Component's model object has already been updated
        target.addComponent(componentToUpdate);
    }
    @Override
    protected void onError(AjaxRequestTarget target, RuntimeException e){
         // Here the Component's model object will remain unchanged, 
         // so that it doesn't hold invalid input
    }
};

Remember that any IFormValidator involving the ajax-ified component will not execute automatically, so you might be interested in checking the input for yourself manually before updating model objects if it's the case. You can tell AjaxFormComponentBehavior not to update model objects automatically by overriding getUpdateModel(). Then, in the onUpdate method, get the component's new input by means of getConvertedInput().

As a side note, onkeyup should be getting fired when pressing the backspace key. At least it does in this fiddle, and onchange is generally triggered on an <input type="text"> when focusing out of it.

Also, HTML5 introduces the oninput event handler, which may better suit your needs. It will get fired even when copying/pasting in the text field. See the following link for more information: Using the oninput event handler with onkeyup/onkeydown as its fallback.

Comments