Tuesday 25 July 2017

Select all checkbox using javascript in visualforce page

1. We can use Javascript in visualforce to select all chechboxes in visualforce table. Below is the example uses javascript to implement functionality.

Click for demo



Visualforce Page:

<apex:page controller="CheckCheckboxUsingJavascriptController" 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="{!wrapperAccountList}" var="accWrap" id="table" title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                    </apex:facet>
                    <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                </apex:column>
                <apex:column value="{!accWrap.acc.Name}" />
                
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public class CheckCheckboxUsingJavascriptController {
    public List<wrapAccount> wrapperAccountList {get; set;}
    
    public CheckCheckboxUsingJavascriptController (){
        if(wrapperAccountList == null) {
            wrapperAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapperAccountList
                wrapperAccountList.add(new wrapAccount(a));
            }
        }
    }
     
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        //This is the contructor. we pass a Account that is set to the acc property. We also set the selected value to false
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}

0 comments:

Post a Comment

If you have any doubts, please let me know.