How to make checkbox in Visualforce page works with slds

The background

Based on current version (Winter 17), I think it is a good time to serious consider moving our existing Visualforce pages into the look and feel of lightning experience, which means we should seriously consider using slds in our Visualforce pages now.

Whether or not using lightning component remains a question for now. I will talk more about the pros and cons of using Lightning component. In this post, I will assume we are not using lightning component.

The problem

In slds, if we want to write a checkbox, we need to do something like this:

<div class="slds-form-element">
  <label class="slds-checkbox" for="checkboxSample1">
    <input name="checkbox" type="checkbox" id="checkboxSample1" >
    <span class="slds-checkbox--faux"></span>
    <span class="slds-form-element__label">Checkbox Label</span>
  </label>
</div>

The problem with this one is, it is hard to set the default value of the checkbox. Use the following code:

<input type="checkbox" name="options" id="isactive-checkbox" checked="{!is_active}" >

will simply not work. It will always be checked. That’s because html won’t check the value inside checked attribute. If there is a checked attribute, it will always be checked.

The solution

I will provide you two solutions here. The easiest one is to use a <apex:inputField> here.

<div class="slds-form-element slds-align--absolute-center">
    <label class="slds-checkbox">
        <apex:inputCheckbox styleClass="slds-input"
                            value="{!Account.Owner.isActive}">
        <span class="slds-checkbox--faux"></span>             
        <span class="slds-form-element__label">Checkbox Label</span>    
    </label>
</div>

The trick here is to remove the for attribute of label. Otherwise, it will not work.

Another solution is to use Javascript method. If there is any reason you don’t want to use Visualforce tags here. you might want to use JQuery to prompt the checkbox value. The jQuery code is as below:

$("#checkbox").prop("checked",{!is_active});

Next Post

How to convert apex:pageMessages to be slds style

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *