Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...