I have two kinds of check boxes. One is a simple check box e.g t:selectBooleanCheckbox
and another is a dynamically generated list of t:selectBooleanCheckbox
. I want to control this list with the single check box. E.g. when it is selected or deselected, similar action should take place for the list as well.
views:
170answers:
1With JSF there are two ways to achieve this.
Submit the form to the server onclick of the checkbox.
<t:selectBooleanCheckbox value="#{bean.selectAll}" onclick="submit()" />
And just do the logic to select/unselect all checkboxes.
public void submit() { for (CheckboxItem item : checkboxItems) { item.setSelected(selectAll); } }
Caveat: not user and developer friendly. User sees flash of content and might have to wait some time before page returns. Developer has to retain all inputs of the same form and hassle with JSF validation, if any.
Use JavaScript to do the magic entirely at the client side.
<t:selectBooleanCheckbox value="#{bean.selectAll}" onclick="selectAll(this)" />
with
function selectAll(checkbox) { var elements = checkbox.form.elements; for (var i = 0; i < elements.length; i++) { var element = elements[i]; if (/checkboxId$/.test(element.id)) { element.checked = checkbox.checked; } } }
This however assumes that all checkbox elements generated by your dynamic list have an ID ending with
checkboxId
. Just check the generated HTML source to spot the pattern. You at least know in which direction you should look now.
Oh, don't forget to write similar logic to unselect the "select all" checkbox whenever one of the checkboxes in the list is unchecked.