Monday, August 29, 2016

Select All records in Pageblock table Visualforce page Using Javascript



Sometime we are displaying list of records in Visualforce page and need to select some or all by click on check box.
If we need to select all records from the list,we can use client side code(java script) to select all records in a single click instead of selecting each one individually or using some server side code to select all records.

Lets create a VF page where we will display all list of record with a select checkbox.

Visualforce page

<apex:page controller="SelectRecordController">
<!--Javascript to select all records-->
    <script type="text/javascript">
        function selectAllRecords(obj,selInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(selInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!wrapRecordList}" var="recWrap" id="table" 
                             title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllRecords(this,'inputId')"/>
                    </apex:facet>
                    <apex:inputCheckbox value="{!recWrap.selected}" id="inputId"/>
                </apex:column>
                <apex:column value="{!recWrap.acc.Name}" />
                <apex:column value="{!recWrap.acc.BillingState}" />
                <apex:column value="{!recWrap.acc.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>



Controller:

public class SelectRecordController {
    public List<wrapRecord> wrapRecordList {get; set;}
     
    public SelectRecordController(){
        if(wrapAccountList == null) {
            wrapRecordList = new List<wrapRecord>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account 
                             limit 10]) {                
                wrapRecordList.add(new wrapRecord(a));
            }
        }
    }
     
    public class wrapRecord {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        
        public wrapRecord(Account a) {
            acc = a;
            selected = false;
        }
    }
}

Output:

When you open this page , all list of records will be displayed with a checkbox in column header.

If you select his check box then JavaScript function will execute and all list of records will be selected.

3 comments: