Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

java - Catch KeyCode in AjaxBehaviorEvent of JSF 2

I have a JSF ajax keyup event linked to an event listner in a backing bean.

The code in the JSF file is like below.

<h:inputText id="txtDescription" value="#{institutionController.current.description}" disabled="#{institutionController.modifyControlDisable}" >
    <f:ajax event="keyup" listener="#{institutionController.changeDetailsEvent}" />
</h:inputText>

The code in the backing bean is like below.

public void changeDetailsEvent(AjaxBehaviorEvent event) {
}

I want to achieve different logic depending on the key presses, like shown is pseudocode below.

public void changeDetailsEvent(AjaxBehaviorEvent event) {
    If (event.key = Key.enter) {
        do something;
    } else if (event.key = Key.Escape) {
        so something else;
    } else {
        do nothing;
    }

}

Can someone please tell me how this is done in the backing bean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The AjaxBehaviorEvent doesn't contain any information about the JavaScript event object. You need to pass the desired information along yourself. This can be achieved by a hidden input field whose value is to be prefilled by JavaScript. For example,

<h:inputText value="#{bean.input}" onkeyup="document.getElementById('#{keyCode.clientId}').value=event.keyCode">
    <f:ajax event="keyup" execute="@this keyCode" listener="#{bean.listener}" />
</h:inputText>
<h:inputHidden id="keyCode" binding="#{keyCode}" value="#{bean.keyCode}" />

(please note that the id of the hidden field is included in execute so that it get submitted along on the ajax request, please also note that the binding is used to be able to dynamically obtain the generated client ID in document.getElementById() in order to set the key code value, you could alternatively also hardcode the client ID if it's fixed)

with

private String input;
private int keyCode;

public void listener() {
    switch (keyCode) {
        case 13:
            // Enter key was pressed.
            break;
        case 27:
            // Escape key was pressed.
            break;
        default:
            // Other key was pressed.
            break;
    }
}

You can find an overview of all valid keyCode values in the Mozilla DOM reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...