Get widgetVar with JavaScript or check/uncheck all other PrimeFaces checkboxes

21,670

You were correct -- if you create your component like this:

<p:selectBooleanCheckbox value="val" widgetVar="myCheckbox"/>

You can access the checkbox simply by refering to its widgetVar, in this case calling the PrimeFaces client-side API to mark it as checked:

<script>
   myCheckbox.check();
</script>

You could then tie the onchange event of your master checkbox to a javascript method that checked or unchecked the state of all the "slave" checkboxes depending on the state of the master checkbox (would suggest you store the state in a hidden field).

Note, it may make your life easier to instead handle the "change" ajax event and implement the check/uncheck logic on the server side. Just make sure that you provide all the ids of all the slave checkboxes in the update attribute of the p:ajax component:

<p:selectBooleanCheckbox id="masterChkBox" ...>
  <p:ajax event="change" listener="#{yourBean.handleMasterChange}" update="...all slavecheckbox ids..."/>
</p:selectBooleanCheckbox>
Share:
21,670
Joel
Author by

Joel

Updated on July 11, 2022

Comments

  • Joel
    Joel almost 2 years

    I have several PrimeFaces checkboxes on a page. If you click the master checkbox, all other checkboxes should be checked/unchecked. With plain HTML checkboxes this would be an easy issue. But because PrimeFaces does not show the checkbox itself, but an image, the following JavaScript code does not work:

    <script type="text/javascript">
    $(document).ready(function() {
        var masterCheckbox = $(".ui-chkbox.master :checkbox");
        var slaveCheckboxes = $(".ui-chkbox:not(.master) :checkbox");
    
        updateMaster();
        masterCheckbox.change(updateSlaves);
        slaveCheckboxes.change(updateMaster);
    
        function updateMaster() {
            var allSlavesChecked = true;
            slaveCheckboxes.each(function() {
                if (!$(this).is(':checked')) {
                    allSlavesChecked = false;
                }
            });
            masterCheckbox.attr("checked", allSlavesChecked);
        }
    
        function updateSlaves() {
            var masterChecked = masterCheckbox.is(":checked");
            slaveCheckboxes.each(function() {
                $(this).attr("checked", masterChecked);
            });
        }
    });
    </script>
    

    I know that I could use the PrimeFaces widgetVar to toggle the checkboxes, but I do not know how to get the PrimeFaces widget objects with JavaScript. I think RichFaces adds the component property to the DOM element, but PrimeFaces does not. Does somebody know a solution for this problem?

  • Joel
    Joel almost 12 years
    Yes, finally I did it as you suggested. Before I had the idea to iterate over all window properties, look for the widget_* properties and check if they belong to a checkbox...