Select all checkboxes by clicking another Primefaces checkbox

Asked

Viewed 3,040 times

3

I have a question, how to select all checkbox that is inside a panelgrid? I saw that it is possible to do this via Avascript.

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

But I don’t know how to perform the method on the first faces.

I’m using the component p:selectManyCheckbox.

<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>

As well as accomplish such a feat?

2 answers

2


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

What I usually do is look for some patterns in the generated HTML, and assemble the script based on these patterns. Then I would make a solution like the following:

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

It seems laborious, but jQuery makes life a lot easier, it’s 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>

    <script language="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>
  • Please how do I call the method in the component? Can I include this in a separate file...

  • 1

    No need to call on component. This line $('input[id*="checkBoxTodas"]').click(checkBoxTodas_onClick); is responsible for searching for the elements that have "checkBoxTodas" in the ID, and then includes the treatment for click events. So just pasting this script on the page should already work (or almost, maybe on the real page need small adjustments but once you understand what the code is doing will be easy)

  • Yes, I need to make some adjustments, because here’s the thing, there are other columns on the page that use styleClass="columnCenter" and then I’ll take it by the id that I will set in the selectManyCheckbox. I even talked to a guy and he told me that Jquery is simple, it’s because I don’t have the tricks to use. But here’s the thing, I’d like to put this code in a separate file, you know? It’s like calling the method at some event?

  • To add in a separate file is the same default, just put the script in the file and the page you use include it with <script src="meu_script.js"></script> No need to call any script, because the Document.onready event will automatically run when loading the page.

  • Yeah, man, thanks, I got it Js, but I’ll pass the method to jQuery.

  • is very strange. But when trying to use JQuery, in the Primefaces it does not perform any function, it calls a file jQuery and is locked in a function.

Show 1 more comment

-1

FOR JSF 2 ,for Selected 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(); //
}       

}

Following link from the original post: https://stackoverflow.com/questions/10585080/how-to-create-effective-select-all-checkbox-in-jsf/40889629#40889629

  • Welcome to the stackoverlow community. While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. For example, how to implement this.

  • I will correct the post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.