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

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?


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>
链接地址: http://www.djcxy.com/p/68544.html

上一篇: 在jsf或primefaces的Listbox中有一个复选框

下一篇: 使用JavaScript获取widgetVar或检查/取消选中所有其他PrimeFaces复选框