Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this:

<p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom"
                    required="true" requiredMessage="Please select a position">
    <f:selectItems value="#{employeeBean.positionList}" var="pos"
                                itemLabel="#{pos.name}" itemValue="#{pos}" />
    <p:ajax process="@this" update="@this"/>
</p:selectOneRadio>

<ui:repeat id="iterator" value="#{employeeBean.positionList}" var="template" varStatus="iterStat">
    <div class="form-group" onclick="document.getElementById('employeeForm:positionRadio:#{iterStat.index}').click();">
        <h:outputText styleClass="form-control" value="#{pos.name}"/>
        <p:radioButton for=":employeeForm:positionRadio" itemIndex="#{iterStat.index}" />
        <div style="display: inline">
            <p style="display: inline">
                <h:outputText value="#{pos.description}"/>
            </p>
        </div>
    </div>
</ui:repeat>

I am trying to ensure that clicking on any part of the div containing a radio button selects it. This behavior is achieved using this line of code:

onclick="document.getElementById('employeeForm:positionRadio:#{iterStat.index}').click();"

While this works partially by triggering a POST request upon clicking, the client-side styles are not updated to reflect the radio button selection. This issue arises because the p:radioButton element is rendered with a hidden input radio and a visible span styled dynamically. The question is why does the span style not update when clicked through JavaScript and is there a way to resolve this?

My technologies include JSF 2.1.7, PrimeFaces 5.0, and Java 1.7

Answer №1

After further exploration of the issue, I have come up with a workaround. Although I am still looking for a better alternative, my current approach involves manually updating styles using JavaScript.

To begin with, I introduced a hidden input field outside the ui:repeat to keep track of the previously selected radio button index:

<input type="hidden" name="prevClicked" id="prevClicked" value="-1"/>

In addition, I assigned an id of raBtn to the p:radioButton inside the ui:repeat and transferred the onclick JavaScript to a function:

function radioBtnDivClicked(event, radioIndex){
    // Check prevClicked field to revert styles if necessary
    if(document.getElementById('prevClicked').value != -1){
        var prevIndex = document.getElementById('prevClicked').value;
        document.getElementById('employeeForm:iterator:' + prevIndex + ':raBtn').children[1].className = 'ui-radiobutton-box ui-widget ui-corner-all ui-state-default';
        document.getElementById('employeeForm:iterator:' + prevIndex + ':raBtn').children[1].children[0].className = 'ui-radiobutton-icon ui-icon ui-icon-blank';
   }

    // Set styles for clicked div
    document.getElementById('employeeForm:positionRadio:' + radioIndex).click();
    document.getElementById('employeeForm:iterator:' + radioIndex + ':raBtn').children[1].className = 'ui-radiobutton-box ui-widget ui-corner-all ui-state-default ui-state-active';
    document.getElementById('employeeForm:iterator:' + radioIndex + ':raBtn').children[1].children[0].className = 'ui-radiobutton-icon ui-icon ui-icon-bullet';
    document.getElementById('prevClicked').value = radioIndex;

    // Stop event bubbling
     event.stopPropagation();
}

This script can be easily converted to jQuery for greater efficiency.

Moreover, I simply modified the onclick attribute to:

onclick="radioBtnDivClicked(event,#{iterStat.index});"

Although this method works, I would prefer a solution where the radio button's style changes are handled by Primefaces when clicked directly.

Answer №2

It appears that you are selecting the incorrect HTML element. Take a closer look at the id attribute of the generated <p:radioButton..., for example, the first button in the custom layout demo on the PrimeFaces showcase:

<div id="j_idt88:opt1" class="ui-radiobutton ui-widget">
    <div class="ui-helper-hidden-accessible">
        <input value="Red" id="j_idt88:customRadio:0_clone" name="j_idt88:customRadio" class="ui-radio-clone" data-itemindex="0" type="radio">
    </div>
    <div class="ui-radiobutton-box ui-widget ui-corner-all ui-state-default">
        <span class="ui-radiobutton-icon ui-icon ui-icon-blank ui-c"></span>
    </div>
</div>

You should trigger a click event on the div with the 'ui-widget' class nested within it

Therefore

$('#j_idt88\\:opt1 .ui-widget').click();  # The \\ is used to escape the colon in the jQuery selector)

This approach has been successful when tested on the PrimeFaces 6.0 showcase

If necessary, consider using your own ids or analyzing any patterns in the automatically generated ids if you do not assign them explicitly.

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

Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter" ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

Understanding the scope within a .when .done function in jQuery

I'm currently grappling with accessing a variable from within a .when.done function. Take a look at this illustrative example: var colviews = { 1: true, 2: true, 3: false } $.when( $.getScript( "/mckinney_images/jquery.tablesorter. ...

There are no elements displayed beneath the div

If you're short on time, let me explain my point with an image: Here is the HTML code I am working with: <div align="center"> <div class="img-container"> <div class="myconatiner"> <h2>Headline< ...

Finding all items in an array in Cypress and validating them using JavaScript assertions

After making an API call, I have received an array response that includes the following information: [ { "IsDatalakeEnabled": true, "RecoveryHr": { "IsRecoveryHREnabled": false, &quo ...

What steps should I take to address this 'key' alert?

My browser console is displaying the following error message: Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...

Is the hidden element still viewable even with display: none?

Can you explain why the icon is still visible when the display is set to none? .toc.item { display: none; } <a class="toc item"><i class="sidebar icon"></i></a> ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...

What is the best way to exclude the "table" property from a button inside a row of a table?

I'm currently working with bootstrap and have implemented a table with the property "table" to create a light background for the data pulled from a database. The design looks great, except for when I try to insert a button in each row for editing purp ...

Looking to utilize the <pre> tag without any external CSS styles defined in a separate stylesheet?

In my current project, I am using bootstreap v3.2. I am facing an issue where I need to display fetched content from the database on a page using the <pre></pre> tags. However, the problem is that the content is being displayed with the default ...

Resizable table example: Columns cannot be resized in fixed-data-table

I've implemented a feature similar to the Facebook example found here: https://facebook.github.io/fixed-data-table/example-resize.html You can find my source code (using the "old" style with React.createClass) here: https://github.com/facebook/fixed- ...

Combine strings in PHP with an alert box in JavaScript

Is there a way to concatenate a string in a JavaScript alert box? I want the first part of the alert box to be a simple text, while the second part is a string retrieved from a MySQL table. $myname = $row["name"]; echo ' <scri ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Enhance the code for updating the content within a div element

I recently discovered that utilizing jQuery allows for updating the content within a div. My goal now is to enhance this script so the content remains consistent, even while loading or not. Take a look at my current code: function changeContent () { va ...

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...