[SalesForce] How to do character count in rich text field

I'm having a custom lightning component in which there is a rich text field present. Now I need to count the characters remaining as the user types. I found that there is no keyup function or max length attribute present in lightning:inputRichText.

Also If any inline image is added, how the character counts behave?

Any ideas would be really appreciated.

<div class="slds-form-element">
        <label class="slds-form-element__label slds-text-color_destructive slds-text-body_regular" for="textareaSample2">Body</label>
          <div>
            <lightning:inputRichText aura:id="commentBody" value="{!v.commentBody}" placeholder = "Enter your comments here">
              <lightning:insertImageButton/>
          </lightning:inputRichText>  
           </div>                    
      </div>

Best Answer

As we cannot add onKeyUp Listener on lightning:inputRichText , we will add a listener to commentBody attribute in the markup. We can do that using aura:valueChange

Markup:

 <aura:attribute name="commentBody" type="String"></aura:attribute>
 <aura:handler name="change" value="{!v.commentBody}" action="{!c.itemsChange}"/>

<div class="slds-form-element">
        <label class="slds-form-element__label slds-text-color_destructive slds-text-body_regular" for="textareaSample2">Body</label>
          <div>
            <lightning:inputRichText aura:id="commentBody" value="{!v.commentBody}" placeholder = "Enter your comments here">
              <lightning:insertImageButton/>
          </lightning:inputRichText>  
           </div>                    
</div>

Javascript :

({
    itemsChange : function(component, event, helper) {
        console.log(component.get("v.commentBody"));
        console.log(component.get("v.commentBody").length);
    }
})

Just to note, its a rich text area, so it would be HTML content so the fonts formating will increase the character length. So the number of chars looking in screen is less than actual char count in the field.

Related Topic