Trigger the change-event by hand

Hey there, I'm facing an issue with manually triggering a change event.

Currently, I have a selectOneMenu (similar to a dropdown in JSF) with various values.

When I select a value from this dropdown list, a datatable is supposed to be updated. This works as expected when I manually choose a value.

However, there's a scenario where I need to add a new value to the selectOneMenu. While this new value gets automatically selected, the change event required to update the datatable doesn't get triggered...

Essentially, I have a button to save a new value to the selectOneMenu, which then gets selected correctly. But the datatable does not update, prompting me to create the function fireChange() and assigning it to the oncomplete attribute of the button:

<p:commandButton ajax="true" id="seatingPlanSave" actionListener="#{EventAssistentController.createSeatingPlan}" value="#{msg.save}" update=":createEvent:EventSeatingPlan, :createEvent:ticketTypePrices" oncomplete="fireChange()"/>

I've attempted various implementations for the fireChange() function:

function fireChange() {
    var element = document.getElementById("createEvent:EventSeatingPlan_input");
    element.change();
}


function fireChange() {
    var element = document.getElementById("createEvent:EventSeatingPlan_input");
    $(element).trigger("change");
}


function fireChange() {
    if ("fireEvent" in element)
        element.fireEvent("onchange");
    else {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        element.dispatchEvent(evt);
    }
}

Unfortunately, none of these solutions seem to work. Could you please provide guidance on how I can achieve this?

Thank you, Xera

Answer №1

You have not provided any information about how the HTML representation of

createEvent:EventSeatingPlan_input
which is essential for us to know in order to correctly implement JavaScript interception. There was no mention of whether you are using <h:selectOneMenu> or <p:selectOneMenu>, making it impossible for us to examine the generated HTML representation ourselves. The former generates a <select><option>, while the latter generates a <div><ul><li> structure that interacts with a hidden <select><option>. Different approaches are required for handling dropdown menus based on their representations in JS. Additionally, details on how the change event handler function is registered are necessary. Is it done by hardcoding the onchange attribute, or by using <f:ajax> or <p:ajax>?

Based on the information provided, I will make an assumption:

<h:selectOneMenu ...>
    <f:ajax render="dataTableId" />
</h:selectOneMenu>

This configuration will produce a

<select onchange="..."><option>
.

Regarding your initial attempt:

function fireChange() {
    var element = document.getElementById("createEvent:EventSeatingPlan_input");
    element.change();
}

This method won't work for <h:selectOneMenu> because the HTMLSelectElement interface does not contain a change property or method. Instead, the correct approach is to use the onchange property that returns an event handler which can be directly invoked by adding ().

The following code snippet will work for <h:selectOneMenu>:

function fireChange() {
    var element = document.getElementById("createEvent:EventSeatingPlan_input");
    element.onchange();
}

However, this method will fail for <p:selectOneMenu> as it returns a HTMLDivElement instead of an HTMLSelectElement. The HTMLDivElement does not have an onchange property that returns an event handler. In the case of <p:selectOneMenu>, which generates a <div><ul><li> widget interacting with a hidden <select><option>, you need to register this widget within the JavaScript context and then utilize its special triggerChange() method.

For example, given:

<p:selectOneMenu widgetVar="w_menu" ...>
    <p:ajax update="dateTableId" />
</p:selectOneMenu>

You should use the following function:

function fireChange() {
    w_menu.triggerChange();
}

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

When should vuex be used for storing data instead of relying on local component data?

Currently I am tackling a complex project that is built using Vue. Our team has opted to use Vuex as our state management system, however there are certain components where the data is not needed elsewhere. Should I follow convention and store this data ...

The installed NPM package does not contain the necessary TypeScript compiled JS files and declaration files

I have recently released a TypeScript library on NPM. The GitHub repository's dist (Link to Repository Folder) directory includes all compiled JavaScript and d.ts files. However, after running npm i <my_package>, the resulting module contains on ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...

Using Javascript to Conceal Button for Unauthenticated Users

Our website is currently running on an outdated e-commerce CMS platform, which limits my options due to my beginner level skills in JavaScript and jQuery. One specific issue we are facing is the need to hide Prices and Add to Cart buttons for users who ar ...

Having trouble with the functionality of the jQuery `has()` method?

Consider the following HTML code snippet: <div class="comment"> <span class="test">some content here</span> <p>Lorem ipsum</p> </div> <div class="comment"> <p>Lorem ipsum</p> </div> The ob ...

Tips for resetting the form input fields in Vue.js after the user has successfully submitted the form

I am facing an issue with my registration page. After the user enters some values and successfully submits the form, I want to clear all the fields. To achieve this, I am using a predefined function called reset() inside the script section. However, the ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

Transfer only certain directories located within the primary directory

Imagine having a main-folder, which contains folders of type my-folder-x. Within these my-folder-x folders, there are subfolders and files. -main-folder -my-folder-a -build-folder -demo-folder dummy.js dummy.css my.json -dummy-folder - ...

Setting innerHTML does not affect the content of an SVG element

I am currently working on an Angular 7 application and I need to dynamically update the text value based on a dropdown selection. For example, if the id of the text element is 10, then I want to change the text from 'hi' to 'hello'. T ...

Unlocking request header field access-control-allow-origin on VueJS

When attempting to send a POST request to the Slack API using raw JSON, I encountered the following error: Access to XMLHttpRequest at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field acces ...

Using jQuery and regex to validate a long string containing lowercase letters, uppercase letters, numbers, special characters, and

Good day, I've been struggling with jquery regex and could really use some assistance. I've been stuck on this since last night and finally decided to seek help :) Here is my regex code along with the string stored in the 'exg' variabl ...

What is the best way to add table pagination at the bottom of a table?

Can someone provide guidance on implementing table pagination for the material-ui table below? The documentation is a bit unclear: <Table ria-label="a dense table"> <TableHead> <TableRow> ...

When working with an array of objects in Vue.js, what is the optimal approach: replacing the entire array or modifying individual values?

I am currently utilizing Vue and Vuex to dynamically generate components from an array retrieved from SQLite using the library better-sqlite3. let table=[ { id:1, column_1:'data', column_2:'data', column_3:{'1&apo ...

Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate ...

The HSET command in the Redis client for Node.js is not working

I have been developing a DAO (data access object) for the project I am currently working on, which acts as an abstraction of a redis database. Below is the code relevant to my upcoming query: var redis = require("redis"); var _ = require("underscore"); va ...

Javascript only select values from the initial row of the table

I have a database that I am using to populate a table with results. To interact with these results, I utilize JavaScript in addition to PHP for retrieving values from the database and displaying them in the table. <table id="datatable" class="table tab ...

Utilizing cheerio to set outerHTML in HTML

Could someone kindly assist me with setting the outerHTML of an element using cheerio? I seem to be encountering some issues with this process. For example, let's consider the following HTML structure: <div class="page-info"> <s ...

Using static assets within VueJS Components

I am currently working on a VueJS project that was customized from a base "webpack-simple" template provided by vue-cli, and it follows the folder structure below: https://i.sstatic.net/C3vxY.png My main focus right now is developing the "clickableimage. ...

"Using regular expressions in a MongoDB find() query does not provide the desired

app.get("/expenses/:month", async (req, res) => { const { month } = req.params; const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d"); console.log(regexp); const allExpenses ...