Select all checkbox when clicking another checkbox of PrimeFaces

3

I'm having a question, how do I select all checkboxes that are inside a panelgrid? I have seen that it is possible to do this via javaScript.

But I was in doubt about how to execute the method because to select all. At first he wanted to see if he really did. Then I made the method to select from the panelgrid id.

But I do not know how to execute the method in primefaces.

I'm using the p:selectManyCheckbox component.

<p:panelGrid styleClass="panelGridCenter" style="width:70%">
    <p:row>
        <p:column >
            <p:panelGrid id="panelEstados" styleClass="panelGridCenter">
                <p:row>
                    <p:column styleClass="columnCenter">
                        <p:selectManyCheckbox value="#{lojaBean.pojo.ufsInss}" layout="grid" columns="4" >
                            <f:selectItems value="#{lojaBean.helper.estados}"/>
                            <f:selectItem id="checkBoxTodas" itemLabel="Todas" itemValue="false"/>
                        </p:selectManyCheckbox>
                    </p:column>
                </p:row>
            </p:panelGrid>
        </p:column>
    </p:row>
</p:panelGrid>

How to do this?

    
asked by anonymous 22.03.2014 / 20:38

2 answers

2

The great difficulty with Javascript customizations on JSF pages is that we have no control over the HTML generated for the browser. Both the structure and component IDs are not under our control, so it becomes difficult to reference them in a script.

What I usually do is look up some patterns in the generated HTML, and build the script based on those patterns. In this case I would make a solution like the following:

Get the elements whose ID contains "checkBoxAll". JSF generates IDs that are unique to them, but all contain the ID you specified. For each of these elements, add the following procedure in the click:
(1) Get the table cell where it is contained. That is, search the parent elements until you find a "td" that has class = columnCenter
(2) Get all the checkboxes contained in this TD. (3) Mark these checkboxes with the same value that is in the checkbox clicked (checkBoxAll).

It seems hard, but jQuery makes life a lot easier, actually quite simple. Here's an example simulating this case:

<html>
  <head>
    <!--
    Na página feita com PrimeFaces nao é preciso o trecho abaixo para 
    importar o JQuery, ele vem de brinde.
    -->
    <script language="javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script><scriptlanguage="javascript">

      /**
      * Funcao a ser disparada quando o checkbox checkBoxTodas for clicado.
      */
      function checkBoxTodas_onClick() {
        // Localiza a celula de class "columnCenter" que esta imediatamente superior
        var parentTd = $(this).parents(".columnCenter").first();

        // Pega referência a todos os filhos que são checkboxes
        var checkboxes = parentTd.find("input[type=checkbox]");

        // Estado do checkbox TODAS
        var check = $(this).is(":checked");

        // Atribui esse mesmo estado aos demais checkboxes
        checkboxes.prop("checked", check);
      }

      /**
      * Adiciona a funcao acima como event handler para todos os checkboxes cujo ID
      * contem "checkBoxTodas".
      * O JSF gerara ids diferentes para cada ocorrencia, mas todos contem a 
      * tal String.
      */
      $(document).ready(function(){
        $('input[id*="checkBoxTodas"]').click(checkBoxTodas_onClick);
      });
    </script>
  </head>

  <body>

    <!--
      O trecho abaixo simula aproximadamente o HTML gerado pelo codigo JSF.
      O checkbox com id="checkBoxTodas" acaba recebendo no HTML um ID bem mais complicado,
      que geralmente não está sob nosso controle.
    -->
    <table border="1">
      <tr>
        <td class="columnCenter">
          A <input type="checkbox" />
          B <input type="checkbox" />
          C <input type="checkbox" />
          D <input type="checkbox" />
          E <input type="checkbox" />
          <br />

          <input type="checkbox" id="form1:panelEstados:checkBoxTodas:blablabla"></input>
          <label for="form1:panelEstados:checkBoxTodas:blablabla">Todas</label>

        </td>
      </tr>
    </table>
  </body>
</html>
    
25.03.2014 / 15:58
-1

For JSF 2, select all rows on datable in selectionMode multiple with paginator = true: In Page

<p:dataTable widgetVar="tableArea" yourtags...>
     <p:ajax  event="toggleSelect" oncomplete="teste()" /> /// toggleSelect is dispared on click to checkbox header
     <p:column id="columnId" selectionMode="multiple"/>

In js:

function test () {

var checked = $(document).find(":checkbox")["0"].checked; ///Find checkbox header and verify if checkbox is checked
if(checked == true){
    PF('tableArea').selectAllRows(); // if true, selectAllRows from datatable
} else {
    PF('tableArea').unselectAllRows(); //
}       

}

Follow the link from the original post: link

    
30.11.2016 / 17:26