user4899447
user4899447

Reputation:

Primefaces onkeyPress triggerevent

I'm doing Primefaces 5.1. In my page use two commandButton Add,Edit button and username Text field. When I press enter in username text field script to perform editbutton click want perform.But it will perform addButton click.I try below code:

<h:head>
<script>
function callEvent(evnt)
{
if(event.keyCode==13)
{
$('editbutton').trigger('click');
}
</script>

</h:head>
<h:form>
<p:inputText id="userNameField" onkeyPress="callerEvent(event)"/>
.....
....
<p:commandButton id="addButton" value="Save" action="#{user.saveButton}"/>
<p:commandButton id="editbutton" value="Edit" action="#{user.editButton}"/>
</h:form>

When I press enter in textfield it will not perform editbutton only trigger with first button that is addbutton.If I change position of button i.e editbutton is first it will perform editbutton.

Upvotes: 1

Views: 4588

Answers (2)

Parkash Kumar
Parkash Kumar

Reputation: 4730

There are two issues in your code:
1. function name is callEvent, but you are using callerEvent with text field keyPress event.
2. id selector for editbutton is not correct to get element.

You can simply do it with jQuery like selector (ends-with) as following:

<p:inputText id="userNameField" />

$("input[id$='userNameField']").on('keypress', function(event) {
    var keycode = event.keyCode ? event.keyCode : event.which;
    if(keycode == '13')
        $("input[id$='editbutton']").get(0).click();    
});

Upvotes: 0

Zim
Zim

Reputation: 1483

You can try with:

<h:form id="user-form">

and:

<script>
   function callEvent(event) {
      if(event.keyCode==13) {
         $('#user-form\\:editbutton').click();
         return false;
      }
</script>

See also:

Default action to execute when pressing enter in a form

Upvotes: 1

Related Questions