How to disable default keyCode event in Primefaces?

1k views Asked by At

When I press the enter key on p:inputText field then automatically triggered p:commandButton. This is not the behaviour I want.

How can I disable the automated triggering?

1

There are 1 answers

0
Mathieu Castets On

You can disable this behaviour by return false in the onkeypress attribute on your h:form.

<h:form onkeypress="if (event.keyCode == 13) return false;">

13 is the key code corresponding to "Enter"

However, this snippet can break your textarea (you want users to be able to hit Enter to get a new line) so I would improve the above snippet and define a custom JS function.

.xhtml

<h:form onkeypress="return doNotSubmitFormOnEnterPress(event)">

.js

function doNotSubmitFormOnEnterPress(event) {

    if (event.keyCode === 13 && !$(event.target).is('textarea')) {
        return false;
    }

    return true;
}