How can I get the clicked item in the ajax method?

这一生的挚爱 提交于 2019-11-29 04:20:59

You're thus interested in the actual value change and not only in the new value. Bring in a valueChangeListener which compares the old value with the new value and prepares some properties which the ajax listener method could intercept on.

E.g.

<h:selectManyCheckbox value="#{bean.selectedItems}" valueChangeListener="#{bean.selectedItemsChanged}" converter="javax.faces.Long">
    <f:selectItems value="#{bean.availableItems}" />
    <f:ajax listener="#{bean.itemSelected}" />
</h:selectManyCheckbox>

with

private Map<String, Long> availableItems; // +getter
private List<Long> selectedItems; // +getter+setter
private Long selectedItem;
private boolean selectedItemRemoved;

@PostConstruct
public void init() {
    availableItems = new LinkedHashMap<String, Long>();

    for (long i = 0; i < 10; i++) {
        availableItems.put("CHKID " + i, i);
    }
}

public void selectedItemsChanged(ValueChangeEvent event) {
    List<Long> oldValue = (List<Long>) event.getOldValue();
    List<Long> newValue = (List<Long>) event.getNewValue();

    if (oldValue == null) {
        oldValue = Collections.emptyList();
    }

    if (oldValue.size() > newValue.size()) {
        oldValue = new ArrayList<Long>(oldValue);
        oldValue.removeAll(newValue);
        selectedItem = oldValue.iterator().next();
        selectedItemRemoved = true;
    }
    else {
        newValue = new ArrayList<Long>(newValue);
        newValue.removeAll(oldValue);
        selectedItem = newValue.iterator().next();
        selectedItemRemoved = false;
    }
}

public void itemSelected(AjaxBehaviorEvent event) {
    System.out.println("Selected item: " + selectedItem);
    System.out.println("Selected item removed? " + selectedItemRemoved);
}

When in the list "selectedItems" you unchecked the end element, the code no call the method itemSelected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!