Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

primefaces - Get p:selectOneRadio value to a JS function

I have a PF's selectOneRadio to choose a file type to download. Also I have a commandButton to call a download servlet using onclick attribute. The problem is that when I choose file type and click the button, the chosen value is of course not yet submitted. I'm looking for some way to get the chosen value available when I click on a 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}');" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to check the selected value on client side, you will need to define widgetVar attribute for your 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 allow the element to be easily found - you can then use it further to check which value was actually selected. I can see two options how to do it:

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 "";
}

Select whichever approach suits you better - both will return either the selected value or an empty string in case nothing has been selected. So all that remains is calling it in you button's onclick , so for example:

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

Tested on PrimeFaces 5.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...