7

As the title says, instead of clicking on the "Save" button after switching to edit-mode, I would like to have the same functionality when pressing the enter/return-key.

I attempted to do this with p:hotkey but apparently p:hotkey will not work with focused editable components.

Is there any other way to do this than delving into JQuery?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
javaMS
  • 401
  • 4
  • 9
  • 20

2 Answers2

8

Is there any other way to do this than delving into JQuery?

Yes, using plain vanilla JS. But this ends up in possibly non-cross-browser-compatible boilerplate code. No kidding, no this isn't possible via JSF as the magic really needs to happen in the client side. As the <p:cellEditor> doesn't support the requested feature (so that it could otherwise just generate the necessary jQuery code all by itself), you need to write it yourself.

Been there, done that:

$(document).on("keydown", ".ui-cell-editor-input input", function(event) {
    if (event.keyCode == 13) {
        $(this).closest("tr").find(".ui-row-editor .ui-icon-check").click();
    }
});

Just put it in some global JS file. This covers all input fields inside cell editors.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    I have a question. Within the same dataTable, I have the cell editor and I also have a commandButton to delete the record. If I click the button to edit and I hit enter, it is doing the delete action and not the edit. How could I make it execute the edit instead of delete? – Erick Sep 08 '15 at 21:42
  • @Erick this probably does the "edit" and then the "delete", due to two handlers for pressing `Enter`key. Try to add "return false" to the first handler. This will prevent executing other event handlers in the chain. See also [my answer](https://stackoverflow.com/a/58268839/522578). – Eugen Labun Oct 07 '19 at 11:36
0

Slightly modified version of the BalusC code (see also PrimeFaces issue 433):

  • prevent adding new row to the table on "Enter" click
  • cancel editing on "Escape" click
$(document).on("keydown", ".ui-cell-editor-input input", function(event) {
    if (event.keyCode == 13) { // Enter
        $(this).closest("tr").find(".ui-row-editor .ui-icon-check").click();
        return false; // prevents executing other event handlers (adding new row to the table)
    }
    if (event.keyCode == 27) { // Escape
        $(this).closest("tr").find(".ui-row-editor .ui-icon-close").click();
        return false;
    }
});
Eugen Labun
  • 2,561
  • 1
  • 22
  • 18