Prevent a form field from being sent to the backing bean by utilizing JavaScript/Ajax

Is there a way to prevent a specific JSF form field from being sent to the backing bean upon submission? I have multiple fields, and I only want to exclude one of them if a certain condition is met in another input field.

I plan to assess the condition using JavaScript and then omit this particular field from the data that gets submitted to the backing bean.

Answer №1

I couldn't find an exact duplicate, but a similar question is addressed in this Stack Overflow thread. The provided solution does not involve using JavaScript.

Instead of opting for a client-side approach as Kukeltje suggested, consider achieving the same outcome with Ajax. For instance, you can create a form where submitting value 1 depends on whether a checkbox is checked or not.

<h:form>
  <h:panelGrid columns="3">
    <h:outputLabel for="check" value="Check"/>
    <h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
      <f:ajax event="change" render="submit"/>
    </h:selectBooleanCheckbox>
    <h:message for="check"/>

    <h:outputLabel for="value1" value="Value 1"/>
    <h:inputText id="value1" value="#{myBean.value1}" required="true"/>
    <h:message for="value1"/>

    <h:outputLabel for="value2" value="Value 2"/>
    <h:inputText id="value2" value="#{myBean.value2}" required="true"/>
    <h:message for="value2"/>

    <h:commandButton id="submit" value="Submit">
      <f:ajax execute="#{myBean.execute()}" render="@form"/>
    </h:commandButton>
  </h:panelGrid>
</h:form>

The logic of which fields to submit is determined by the <f:ajax execute="..." attribute of the command button, which should contain one or more client IDs separated by spaces. In this scenario, the value is dictated by the backing bean:

public String execute() {
  return checked ? "value1" : "value2";
}

This decision is based on the value of checked, linked to the checkbox. If checked, value1 will be executed; otherwise, value2.

To update the command button's execute attribute, I utilized

<f:ajax event="change" render="submit"/>
for the checkbox to trigger the update of the command button (and its execute client IDs).

Including the 'required' attribute in the fields demonstrates that an error message will display if both are left empty.

Achieving a similar effect by utilizing the 'rendered' attribute of the input fields:

<h:form>
  <h:panelGrid columns="3">
    <h:outputLabel for="check" value="Check"/>
    <h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
      <f:ajax event="change" render="@form"/>
    </h:selectBooleanCheckbox>
    <h:message for="check"/>

    <h:outputLabel for="value1" value="Value 1"/>
    <h:inputText id="value1" value="#{myBean.value1}" required="true"
                 disabled="#{not myBean.checked}"/>
    <h:message for="value1"/>

    <h:outputLabel for="value2" value="Value 2"/>
    <h:inputText id="value2" value="#{myBean.value2}" required="true"
                 disabled="#{myBean.checked}"/>
    <h:message for="value2"/>

    <h:commandButton id="submit" value="Submit">
      <f:ajax execute="@form" render="@form"/>
    </h:commandButton>
  </h:panelGrid>
</h:form>

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

Will my variables become unbound when a new object is created?

Currently, I am developing a component within my Angular application where I am binding an object: CustomComponent.js angular.module("app").component( "customComponent", { controller: function() { var ctrl = this; ctrl.createInstance ...

Loading a file directly into a designated memory block within a Node.js environment

Is it feasible to have Node.js load a file as binary data into a specific memory slot? let buffer = new Uint8Array let location = 0 let path = 'foo.binary' fs.readIntoMemoryLocation(path, buffer, location) Could something like this be achieved? ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

How should I fix the error message "TypeError encountered while attempting to import OrbitControls"?

Encountering error while attempting to import OrbitControls JS: import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window. ...

What is the process for extracting query parameters from an HTTP client and transmitting them to a Node.js server?

Despite extensive searching, I have not been able to find a solution for sending query parameters in a get request. Below is the Node.js server-side code that I have been working with: let propertiesObject = {q: 'lord of the rings'}; let url = ht ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

Retrieving PHP form values using JQuery

How can I transfer a form input value from a PHP file to a JavaScript file? Here is the code I am currently using: <html> <head> <meta charset = "UTF-8"> <title> Search Customer by Field </title> <s ...

What could be causing the onclick function in the button tag to malfunction?

I have implemented a feature where clicking on a "Delete Photo" button would trigger the appearance of another delete button in the code. The code for this functionality is as follows: <button type="button" class="btn btn-danger" onc ...

Managing iframes in React using reference methods

Trying to set the content of an iframe within a React component can be a bit tricky. There is a component that contains a handleStatementPrint function which needs to be called when the iframe finishes loading. The goal is to print the loaded iframe conten ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

Leveraging Directive Class Scope Variable in Controller Class with Angular and Typescript

Struggling with Angular Typescript once again, this time dealing with directives and controllers. I am attempting to pass an object from a page to a directive and then utilize that object in the controller of the directive. While it may not be the most eff ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

The art of connecting Javascript commands in succession

I'm struggling to grasp the concept of chaining and return in JavaScript. For example, consider the following code snippet: let array = [1, 2, 3] let newArray = array.map(val => val * 10).map(val => val * 10) console.log(newArray) // [100, 200, ...

myObject loop not functioning properly in Internet Explorer version 10

Could someone please point out what is wrong with this code snippet? HTML: <div id="res"></div> Javascript: var myObject = { "a" : { src : "someimagepath_a.png" }, "b" : { src : "someimagepath_b.png" }, }; va ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...

The error message "cordova is not defined" is indicating that the cordova.js file has already been loaded

While the app is running, I encountered the following: Uncaught ReferenceError: cordova is not defined ionic-core.js:466 Ionic Core: init ionic-core.js:145 Ionic Core: searching for cordova.js ionic-core.js:149 Ionic Core: cordova.js has already been load ...

Is it possible to incorporate various colors into an SVG image using HTML, specifically with d3.js?

Is it possible to dynamically fill different parts of an SVG image with colors based on data using HTML, CSS, and JavaScript? I have a project in Angular that utilizes D3.js. Here is an example image for reference, where the arms, head, and legs are fill ...

Implementing manual updates for the bootstrap color picker

I have integrated a color picker from Bootstrap into my project. You can find the color picker here: To change the background color of an element on my page, I am using the following code: <input type="text" id="mypicker" name="mypicker" value="" cla ...

When using JSON.parse, a correct JSON string may unexpectedly produce a token error

This question has been asked several times before, but the answers provided did not help me. I have a JSON string that looks like this: var jsonData = { "target1": [ {"x":"222", "y":"333", "WPtext":"go right"}, {"x":"444", "y":"444", "WPtext":"go left"} ] ...