Using jquery in lightning Components

In this blog post, I am going to explain how to use the jquery in the lightning component with well know example of calculating remaining character count.

Step 1: download Jquery javascript file

download the jquery latest version from the https://jquery.com/download/ .

Step 2: Upload to the static resource

Step 3: Time to code!

Here is the simple code that will display the total remaining character from the input text area.

<aura:component >
    <ltng:require scripts="{!$Resource.jQueryv3}"
                  afterScriptsLoaded="{!c.loadJquery}" />
    
    <aura:attribute name="text" type="String" default="" />
    
    <textarea id="textareaChars" maxlength="100" value="{!v.text}"></textarea> <br/>
    
    <span id="chars">100</span> characters remaining   
    
</aura:component>

 

({
    loadJquery : function(component, event, helper) {
        jQuery(document).ready(function(){
            var maxLength = 100;
            $('textarea').keyup(function() {
                var length = $(this).val().length;
                var length = maxLength-length;
                $('#chars').text(length);
            });
        });
    }
})

 

1. Load the Jquery from Static Resource by using ltng:require  . Load the Jquery functionality on afterScriptsLoaded method.

<ltng:require scripts="{!$Resource.jQueryv3}" afterScriptsLoaded="{!c.loadJquery}" />

2.  Load Jquery document  Read method inside the loadJquery function

jQuery(document).ready(function(){
}

3. Use the keyup event on the textarea, which fires each time a key is pressed when the textarea is in focus. Ideal:

$('textarea').keyup(function() {

4. Check the value and get the length of it, store it in a variable:

var length = $(this).val().length;

5. Take that value away from your max width:

var length = maxLength-length;

6. Put the result somewhere on the page:

$('#chars').text(length);