Select All Checkbox Using Javascript in Visualforce Page

Controller:

public with sharing class Sample { 

    public List<AccountWrapper> accountWrapperList {get; set;}
    
    public Sample (){
        if(accountWrapperList == null) {
            accountWrapperList = new List<AccountWrapper>();
            for(Account a: [SELECT Id, Name From Account Limit 10]) {
                accountWrapperList.add(new AccountWrapper(a));
            }
        }
    }
     
    public class AccountWrapper {
        public Account acc {get; set;}
        public Boolean isSelected{get; set;}
 
        public AccountWrapper(Account a) {
            acc = a;
            isSelected = false;
        }
    }  
    
}

Visualforce Page:

<apex:page controller="Sample" sidebar="false" showHeader="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,InputID){
            var inputCheckBox = document.getElementsByTagName("input");    
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(InputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accountWrapperList}" var="a" id="table" title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                    </apex:facet>
                    <apex:inputCheckbox value="{!a.isSelected}" id="inputId"/>
                </apex:column>
                <apex:column value="{!a.acc.Name}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

  • Ajaysing Rajput

    @Biswajeet – What is ‘inputId’ in above snippet.
    I want to implement the same in my code.