Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet:

<p:inputText value="#{customerLController.surnameFilterConstraint}"
             id="surnamefilterfield">
    <p:ajax event="keyup" 
            update=":custForm:custDataTable"
            listener="#{customerLController.focusSurname}"
            oncomplete="primeFacesId('surnamefilterfield')"/>
</p:inputText>

The issue here is that the code triggers Ajax even with arrow key strokes (which I want to avoid due to the expensive update). Ideally, I would prefer an alternative version of p:ajax event="change" with a condition to trigger change events on keystrokes rather than when the user presses Enter key (the current behavior).

If the p:ajax component does not provide a way to filter out specific keyup events, then it seems like the only (?) solution would be to execute JavaScript on the client side and handle the Ajax call in JavaScript. However, this would mean sacrificing the convenience of using the PrimeFaces p:ajax component, right?

Answer №1

Ever since the introduction of JSF 2.2, I have found a more elegant solution to this problem.

The solution involves utilizing both p:remoteCommand (as mentioned in a comment) and the use of namespace

http://xmlns.jcp.org/jsf/passthrough
, which enables you to incorporate native HTML event attributes into JSF components.

To implement this solution:

  1. Begin by adding a new namespace to your page

    xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
    
  2. Next, modify p:inputText and include p:remoteCommand

    <p:inputText id="surnamefilterfield" 
              value="#{customerLController.surnameFilterConstraint}" 
              pt:onkeyup="onKeyUpFilterKeyCode(event)" />
    <p:remoteCommand delay="300" name="onFilteredKeyUp" 
                  actionListener="#{customerLController.focusSurname}" /> 
    
  3. Add the JavaScript function

    function onKeyUpFilterKeyCode(event){
            var keyCode=event.keyCode;
            console.log("Key code = " + keyCode);
            //if key is not ENTER and not cursor/arrow keys
            if ((keyCode != 13) && !((keyCode >= 37) && keyCode <= 40)){
                //call remoteCommand
                onFilteredKeyUp();
            }
        }
    

(since this JS function contains "special" XML chars follow BalusC recommendations about how to add it to JSF/XML web page)

This approach offers the advantage of being able to ajaxify any native HTML event supported by the component (and web browser), all while still using JSF/Primefaces components in building web pages in the traditional "JSF way".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The inefficiency of invoking Jquery on elements that do not exist for the purpose of caching

What is the impact if JQuery attempts to access elements that do not exist? Will there be any significant CPU overhead other than script loading? Does it matter if this is done for a class or an id? For optimization purposes and to minimize simultaneous c ...

What is the best way to instantiate a dynamic object within a literal?

I am dealing with an object that contains multiple fields, mainly consisting of constant string values. However, I also need to incorporate a variable that is determined by the current state. const {order} = this.state; myObject={{ fieldA: 2, fiel ...

Total Output Calculation

In my latest coding project, I have crafted a unique algorithm to calculate exam scores with the inclusion of interactive buttons! function incorrectResponse() { var calc = 0; var calc2 = 1; var divElement = document.createElement("div"); divEle ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

ajax not correctly handling errors when SQL connection fails

When using ajax to make a request to a PHP page that connects to a MySQL database, I encountered an issue. Even if the MySQL service is turned off, the success part of the ajax call still triggers. $.ajax({ type: "POST", url: "ajax.php", time ...

Formula for determining the slider's span

I recently created a range slider using Vue.js It has a minimum and maximum value, assumed to be percentages as it ranges from 0 to 100. My goal is to set the minimum value at $5,000 and the maximum at $200,000, However, I struggle with math and need th ...

"Exploring the dynamic world of AJAX events in the select

Currently, I am utilizing an editable primefaces selectOneMenu to exhibit certain values. The desired functionality is that when a user chooses an item from the list, a textarea should be automatically updated. On the other hand, if the user manually types ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

Sharing data between view and controller in Laravel: a guide

Currently, I am developing a product cart feature that includes subtotal and grand total values displayed within <span> tags. My goal is to pass the grand total value to the controller for further processing. However, I encountered an issue where the ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Launching ng-app for AngularJS after the page has finished loading

After loading content with jQuery AJAX that includes ng-app="" and other directives, the AngularJS initialization does not occur. How can I initialize an ng-app that was added after the page has already been loaded? <script src="https://ajax.googleap ...

Determine the radius using three given points

I am in need of determining the radius at the corners of a rectangle based on some given data points along the curve. The image below provides a visual representation: https://i.stack.imgur.com/7FHq0.png How can I calculate the radius using these specifi ...

The callback function within the Service does not execute just once when utilizing $timeout

Looking to implement a service that functions similarly to this example. Here is the code I have so far: app.service('Poller', function ($q, $http, $timeout) { var notification = {}; notification.poll = function (callback, error) { return $ ...

What is the process of choosing a language (English/French) within a pop-up?

<body style="text-align:center"> <h2>Popup</h2> <div class="popup" onclick="myFunction()">Interact with me to show/hide the popup! <span class="popuptext" id="myPopup">A Simple Popup!</span> </div> <script& ...

Triggering an Angular AJAX call by selecting a radio button

I am currently working on implementing a CRUD functionality in my app for the admin console. My tech stack includes MongoDB, Spring, Bootstrap, and Angular. The interface consists of a list of radio buttons on the left side containing names of collections ...

Where can I locate the Socket.IO server within the local area network (LAN)?

I am currently in the process of developing an application that facilitates connections between devices within the same network. In my design, any device can act as a server, and I aim for clients to automatically detect the server without requiring users ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

Transferring a zipped file from the backend of SailsJS to the frontend of React Redux via

My SailsJS Backend is responsible for generating a zip File when requested by my React App with Redux on the Frontend. I am utilizing Sagas for asynchronous calls and fetch to make the request. In the backend, I have attempted various methods such as: //z ...

What is causing the list to not populate in this code snippet?

How can I populate file paths in a list of strings List<string> img = new List<string>(); when files are posted by the client using dropzone js? The files upload successfully but the list remains empty. Any suggestions on how to resolve this ...