Get p: selectOneRadio value for JS function

I have PF selectOneRadio to select the file type to upload. Also I have a commandButton to call the upload servlet using the onclick attribute. The problem is that when I select the file type and click the button, the selected value is of course not sent yet. I am looking for a way to get the selected value when I click the download button.

Here's my code:

<p:selectOneRadio id="sorType" value="#{bean.type}" layout="custom">
    <f:selectItem itemLabel="XML" itemValue="XML" />
    <f:selectItem itemLabel="XLS" itemValue="XLS" />
    <f:selectItem itemLabel="CSV" itemValue="CSV" />
</p:selectOneRadio>

<p:commandButton type="button" ajax="false" onclick="return downloadFile('#{bean.type}');" />

      

0


source to share


2 answers


If you want to validate the selected value on the client side, you need to define an attribute widgetVar

for yours p:selectOneRadio

, for example:

<p:selectOneRadio widgetVar="widgetSorType" id="sorType" value="#{bean.type}"
    layout="custom">

    <f:selectItem itemLabel="XML" itemValue="XML" />
    <f:selectItem itemLabel="XLS" itemValue="XLS" />
    <f:selectItem itemLabel="CSV" itemValue="CSV" />
</p:selectOneRadio>

      

This will make it easy to find the item - you can use it further to check which value was selected. I can see two options for how to do this:

function getSelectedTypeVer1() {
    return PF('widgetSorType').getJQ().find(':checked').val() || "";
}

function getSelectedTypeVer2() {
    var inputs = PF('widgetSorType').inputs;

    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked) {
            return inputs[i].value;
        }
    }

    return "";
}

      



Choose the one that works for you - both return either the selected value or an empty string if nothing is selected. So all that's left is calling it in your button onclick

, so for example:

<p:commandButton type="button" ajax="false"
    onclick="return downloadFile(getSelectedTypeVer1());" />

      

Tested on PrimeFaces 5.2

+2


source


The solution shared by @ Sva.Mu didn't work for me.

I have an implementation very similar to the latest showcase in PrimeFaces Showcase, which is referenced by custom layouts with some <p:radioButton>

pointing to native <f:selectItem>

.



Instead of using PF('widgetName').getJQ().find(':checked').val();

I have succeeded with PF('widgetName').inputs.filter(':checked').val();

combining both approaches in some way.

My PrimeFaces version: 6.1

0


source







All Articles