Question

Comment obtenir quelle radio est sélectionnée dans p:selectOneRadio en utilisant javascript / jquery?

Comme le p:selectOneRadio n'utilise pas de balises radio, je n'ai aucune idée de comment obtenir l'option cochée à l'aide des sélecteurs CSS.

    <p:selectOneRadio onchange="reactToChangedRadio()" >
              <f:selectItem itemLabel="....." itemValue="..." />
              <f:selectItem itemLabel="....." itemValue="..." />
              <f:selectItem itemLabel="....." itemValue="..." />
    </p:selectOneRadio>
Était-ce utile?

La solution

Vous pouvez utiliser la solution jquery ou choisir une solution javascript simple:

document.getElementById("myFormId:mySelectId")[0].checked 

Voir l'article de CodeRanch: http:// www. coderanch.com/t/210871/JSF/java/selectOneRadio-javascript-value

MISE À JOUR: Je dois admettre que je suis dans un département, et j'en suis désolé mais hier je n'ai pas eu beaucoup de temps ...

Je dois dire que je n'ai pas été en mesure d'obtenir la valeur radio de la manière javascript à l'ancienne:

                 <script type="text/javascript">
                      /*  <![CDATA[ */

                        function reactToChangedRadio(){
                           alert("I'm in!");
                           var myval;
                            for(i=0;i<3;i++){
                                    if(document.forms['myFormId']['myFormId:myRadio'][i].checked == true ){
                                        myval = document.forms['myFormId']['myFormId:myRadio'].text/value;
                                    }
                                }
                                alert( "val = " + myval );
                        }
                    /*    ]]> */
                </script>

En revanche, cette solution codée en dur fonctionne:

                 <script type="text/javascript">
                      /*  <![CDATA[ */

                        function reactToChangedRadio(){
                           alert("I'm in");
                           var myval;
                           if(document.forms['myFormId']['myFormId:myRadio'][0].checked == true ){
                              myval = "first button";
                           }else if(document.forms['myFormId']['myFormId:myRadio'][1].checked == true ){
                              myval = "second button";
                           }else if(document.forms['myFormId']['myFormId:myRadio'][2].checked == true ){
                              myval = "third button";
                           }

                           alert( "val = " + myval );
                        }
                    /*    ]]> */
                    </script>

, mais bien sûr, en raison de la puissance de Primefaces, il existe une solution côté serveur (utilisant le composant ReuqestContext):

                 <h:form id="myFormId">
                        <p:selectOneRadio id="myRadio" value="#{handleFiles.radioVal}" >
                            <p:ajax event="change" oncomplete="handleComplete(xhr, status, args)" listener="#{handleFiles.testMethod}" />
                            <f:selectItem itemLabel="1" itemValue=" first" />
                            <f:selectItem itemLabel="2" itemValue=" second" />
                            <f:selectItem itemLabel="3" itemValue=" third" />
                        </p:selectOneRadio>
                    </h:form>
<script type="text/javascript">
 function handleComplete(xhr, status, args) {  
    alert("Selected Radio Value" + args.myRadVal);  
 } 
</script>

Le code côté serveur:

private String radioVal;

public String getRadioVal() {
    return radioVal;
}

public void setRadioVal(String radioVal) {
    this.radioVal = radioVal;
}

public void test(){
    RequestContext context = RequestContext.getCurrentInstance();  
    context.addCallbackParam("myRadVal", radioVal);
    System.out.println("radioVal: "+radioVal);
}

Le composant ReuqestContext peut être trouvé ici: http://www.primefaces. org / showcase-labs / ui / requestContext.jsf (uniquement pour PF 3)

Autres conseils

The problem could be solved easily with jquery find() by using getJQ method of the pf widget:

<p:selectOneRadio ... widgetVar="mySelectName" .../>

we can obtain current value by calling:

PF('mySelectName').getJQ().find(':checked').val();

If you just need the value of selected item in JS you can call your function with this.value parameter. Look inside PF generated HTML:

<input id="{component_id}:{index}" name="{component_id}" type="radio" value="{itemValue}"
    checked="checked" onchange="reactToChangedRadio(this.value);">
...

for each selectItem. Hence this.value works perfectly, no need to search for checked:

<script>
    function reactToChangeRadio(par){
        alert('Value of selected item is: ' + par);
    }
</script>

<p:selectOneRadio onchange="reactToChangedRadio(this.value);" >
          <f:selectItem itemLabel="....." itemValue="..." />
          <f:selectItem itemLabel="....." itemValue="..." />
          <f:selectItem itemLabel="....." itemValue="..." />
</p:selectOneRadio>

Or you can pass this.id into function to use it in jQuery selector.

you have yo use the :checked pseudo selector: More info here: http://api.jquery.com/checked-selector/

 $(":checked")

All you need to do is to disable all radio buttons except the one that was checked like:

<h:selectOneRadio id="rad" ... onclick="dataTableSelectOneRadio(this)" >
  <f:selectItems .... />
</h:selectOneRadio>

And here is your script:

function dataTableSelectOneRadio(radio){
      var id = radio.name.substring(radio.name.lastIndexOf(':'));
      var temp = radio.name.lastIndexOf(':') - 1;
      var index = radio.name.substring(temp,temp+1);
      var el = radio.form.elements;

       for(var i = 0 ; el.length; i++)
       {
          if(el[i].name.substring(el[i].name.lastIndexOf(':')) == id) {
              if(el[i].name.indexOf(index) != -1)
                  el[i].check = true;
              else
                   el[i].check = false;

           }
       }

}

There is a one-line solution to this question that also handles the case where you have multiple selectOneRadio inputs on a page.

If your form is called myForm, and your selectOneRadio input has the id myRadio, then the following line will get the selected value:

$('[id^=myForm\\:myRadio]:checked').val()

This works because all the internal inputs are given an id beginning with myForm:myRadio. The line above finds all entities beginning with that string, and selects only the checked ones. Since only one radio button can be checked a a time, this gives the selected radio button. Then we can simply grab its value.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top