Thursday 23 March 2017

How to check if at least one check box is selected in Apex Page BlockTable

Hi folks,

I would like to touch a very common scenario we had to check if at least item (from checkbox) is selected from a data table before submitting the form.

I have implemented it as below:

<apex:page Controller="myController">
<apex:includeScript value="{!URLFOR($Resource.jsFiles, 'jquery-1.7.1.min.js')}" />
<apex:includeScript value="{!URLFOR($Resource.JQueryUI, 'jquery-ui-1.11.2/jquery-ui.min.js')}"></apex:includeScript>
<script>
j$ = jQuery.noConflict();
function Save() {
                if(j$(".selectionCheckbox:checked").length == 0){
                          alert('Please select at least one Item.');
                       }
                       else {
                        // Call action function to go ahead to save
                       }                
                }
</script>
<apex:pageBlock id="pbId" >
<apex:pageBlockTable value="{!SampleDataList}" var="RelatedData">
<apex:column >
<apex:facet name="header">
<apex:inputCheckbox id="checkAll"
onClick="jQuery('.selectionCheckbox').attr('checked', this.checked);" />
</apex:facet>
<apex:inputCheckbox styleClass="selectionCheckbox"
id="myCheckbox" value="{!RelatedData.isSelected}" />
</apex:column>
<apex:column value="{!RelatedData.Name}" />
</apex:pageBlockTable>
</apex:pageBlockTable>
<apex:commandButton value="Save" onclick="Save(); return false;"
rerender="pbId" />
</apex:page>

No comments:

Post a Comment