Es5 getting started in EJ2 JavaScript Smart TextArea control

25 Sep 202424 minutes to read

The Essential JS 2 for JavaScript (global script) is an ES5 formatted pure JavaScript framework which can be directly used in latest web browsers.

The Smart TextArea is an advanced control designed to elevate the text input experience by providing intelligent autocomplete suggestions for entire sentences through text-generative AI functionality. This control enhances user productivity by predicting and offering relevant completions based on the context of what is being typed.

Prerequisites

To get started, ensure the following software to be installed in the machine.

Check out the download and installation section of Essential Studio JavaScript. If you are using Syncfusion CDN resources to build your web application, you can skip the Essential Studio JavaScript prerequisite.

Dependencies

The following list of dependencies are required to use the Smart TextArea control in your application.

|-- @syncfusion/ej2-inputs
    |-- @syncfusion/ej2-base

Control Initialization

The Essential JS 2 JavaScript controls can be initialized by using either of the following ways.

  • Using local script and style references in a HTML page.
  • Using CDN link for script and style reference.

Using local script and style references in a HTML page

Step 1: Create an app folder quickstart for getting started.

Step 2: You can get the global scripts and styles from the Essential Studio JavaScript (Essential JS 2) build installed location.

Syntax:

Dependency Script: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\{DEPENDENCY_PACKAGE_NAME}\dist\global\{DEPENDENCY_PACKAGE_NAME}.min.js

Control Script: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\{PACKAGE_NAME}\dist\global\{PACKAGE_NAME}.min.js

Dependency Styles: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\{DEPENDENCY_PACKAGE_NAME}\styles\material.css

Control Styles: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\{PACKAGE_NAME}\styles\material.css

Example:

Dependency Script: C:\Program Files (x86)\Syncfusion\Essential Studio\JavaScript - EJ2\19.3.0.44\Web (Essential JS 2)\JavaScript\ej2-base\dist\global\ej2-base.min.js

Control Script: C:\Program Files (x86)\Syncfusion\Essential Studio\JavaScript - EJ2\19.3.0.44\Web (Essential JS 2)\JavaScript\ej2-inputs\dist\global\ej2-inputs.min.js

Dependency Styles: C:\Program Files (x86)\Syncfusion\Essential Studio\JavaScript - EJ2\19.3.0.44\Web (Essential JS 2)\JavaScript\ej2-base\styles\material.css

Control Styles: C:\Program Files (x86)\Syncfusion\Essential Studio\JavaScript - EJ2\19.3.0.44\Web (Essential JS 2)\JavaScript\ej2-inputs\styles\material.css

The below located script and style file contains all Syncfusion JavaScript (ES5) UI control resources in a single file.

Scripts: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\ej2\dist\ej2.min.js

Styles: **(installed location)**\Syncfusion\Essential Studio\JavaScript - EJ2\{RELEASE_VERSION}\Web (Essential JS 2)\JavaScript\ej2\material.css

The Custom Resource Generator (CRG) is an online web tool, which can be used to generate the custom script and styles for a set of specific controls. This web tool is useful to combine the required control scripts and styles in a single file.

Step 3: Create a folder ~/quickstart/resources and copy/paste the global scripts and styles from the above installed location to quickstart/resources/package corresponding package location.

Step 4: Create a HTML page (index.html) in ~/quickstart/index.html location and add the Essentials JS 2 script and style references.

<!DOCTYPE html>
  <html xmlns="http://www.w3.org/1999/xhtml">
       <head>
          <title>Essential JS 2 - Smart TextArea</title>
          <!-- Essential JS 2 Inputs's dependent material theme -->
          <link href="resources/base/material.css" rel="stylesheet" type="text/css"/>

          <!-- Essential JS 2 Smart TextArea's control material theme -->
          <link href="resources/inputs/material.css" rel="stylesheet" type="text/css"/>

          <!-- Essential JS 2 Inputs's dependent global script -->
          <script src="resources/base/ej2-base.min.js" type="text/javascript"></script>

          <!-- Essential JS 2 Inputs's control global script -->
          <script src="resources/inputs/ej2-inputs.min.js" type="text/javascript"></script>
       </head>
       <body>
       </body>
  </html>

Step 5: Now, add the Smart TextArea element and initiate the Syncfusion JavaScript Smart TextArea control in the index.html by using following code. In Smart TextArea, the aiSuggestionHandler property, which sends prompts to the AI model and receives context-aware suggestions. These suggestions appear inline for non-touch devices and as an overlay popup for touch devices by default, helping users type faster and more accurately.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Essential JS 2 - Smart TextArea</title>
    <!-- Essential JS 2 Inputs's dependent material theme -->
    <link href="resources/base/material.css" rel="stylesheet" type="text/css"/>

    <!-- Essential JS 2 Smart TextArea control material theme -->
    <link href="resources/inputs/material.css" rel="stylesheet" type="text/css"/>

    <!-- Essential JS 2 Smart TextArea dependent global script -->
    <script src="resources/base/ej2-base.min.js" type="text/javascript"></script>

    <!-- Essential JS 2 Smart TextArea control global script -->
    <script src="resources/inputs/ej2-inputs.min.js" type="text/javascript"></script>
</head>

<body>
    <!--element which is going to render-->
    <div>
        <textarea id="smart-textarea"></textarea>
    </div>

    <script>
        // initialize Smart TextArea control
        const serverAIRequest = async (settings) => {
            let output = '';
            try {
                console.log(settings);
                const response = await (window).AzureAIRequest(settings);
                console.log("Success:", response);
                output = response;
            } catch (error) {
                console.error("Error:", error);
            }
            return output;
        };

        let textareaObj = new ej.inputs.SmartTextArea({
            placeholder: 'Enter your queries here',
            floatLabelType: 'Auto',
            resizeMode: 'Both',
            rows: 3,
            cols: 35,
            userRole: 'Employee communicating with internal team',
            UserPhrases: [
                "Please find the attached report.",
                "Let's schedule a meeting to discuss this further.",
                "Can you provide an update on this task?",
                "I appreciate your prompt response.",
                "Let's collaborate on this project to ensure timely delivery."
            ],
            aiSuggestionHandler: serverAIRequest
        });
        textareaObj.appendTo('#smart-textarea');

    </script>
</body>

</html>

Step 6: Now, run the index.html in web browser, it will render the Syncfusion JavaScript Smart TextArea control.

Step 1: Create an app folder quickstart for getting started.

Step 2: The Essential JS 2 control’s global scripts and styles are already hosted in the below CDN link formats.

Syntax:

Dependency Script: https://cdn.syncfusion.com/ej2/{DEPENDENCY_PACKAGE_NAME}/dist/global/{PACKAGE_NAME}.min.js

Control Script: https://cdn.syncfusion.com/ej2/{PACKAGE_NAME}/dist/global/{PACKAGE_NAME}.min.js

Dependency Styles: https://cdn.syncfusion.com/ej2/{DEPENDENCY_PACKAGE_NAME}/styles/material.css

Control Styles: https://cdn.syncfusion.com/ej2/{PACKAGE_NAME}/styles/material.css

Example:

Script: https://cdn.syncfusion.com/ej2/ej2-inputs/dist/global/ej2-inputs.min.js

Styles: https://cdn.syncfusion.com/ej2/ej2-inputs/styles/material.css

Step 3: Create a HTML page (index.html) in ~/quickstart/index.html location and add the CDN link references. Now, add the Smart TextArea element and initiate the Syncfusion JavaScript Smart TextArea control in the index.html by using following code.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Essential JS 2 - Smart TextArea</title>
    <!-- Essential JS 2 Inputs's dependent material theme -->
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" type="text/css"/>

    <!-- Essential JS 2 Smart TextArea control material theme -->
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-inputs/styles/material.css" rel="stylesheet" type="text/css"/>

    <!-- Essential JS 2 Smart TextArea dependent global script -->
    <script src="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/dist/global/ej2-base.min.js" type="text/javascript"></script>

    <!-- Essential JS 2 Smart TextArea control global script -->
    <script src="https://cdn.syncfusion.com/ej2/27.1.48/ej2-inputs/dist/global/ej2-inputs.min.js" type="text/javascript"></script>
</head>

<body>
    <!--element which is going to render-->
    <div>
        <textarea id="smart-textarea"></textarea>
    </div>

    <script>
        // initialize Smart TextArea control
        const serverAIRequest = async (settings) => {
            let output = '';
            try {
                const response = await (window).AzureAIRequest(settings);
                output = response;
            } catch (error) {
                console.error("Error:", error);
            }
            return output;
        };

        let textareaObj = new ej.inputs.SmartTextArea({
            placeholder: 'Enter your queries here',
            floatLabelType: 'Auto',
            resizeMode: 'Both',
            rows: 3,
            cols: 35,
            userRole: 'Employee communicating with internal team',
            UserPhrases: [
                "Please find the attached report.",
                "Let's schedule a meeting to discuss this further.",
                "Can you provide an update on this task?",
                "I appreciate your prompt response.",
                "Let's collaborate on this project to ensure timely delivery."
            ],
            aiSuggestionHandler: serverAIRequest
        });
        textareaObj.appendTo('#smart-textarea');

    </script>
</body>

</html>

Adding Smart TextArea control to the application

  • Add the HTML textarea tag with the id attribute as Smart TextArea to your index.html file. The following example shows the Smart TextArea control.

In our demonstration, Azure AI is used, but you can integrate any text-generative AI of your choice.

ej.base.enableRipple(true);

/**
 * Smart TextArea sample
 */
const serverAIRequest = async (settings) => {
    let output = '';
    try {
        console.log(settings);
        const response = await (window).AzureAIRequest(settings);
        console.log("Success:", response);
        output = response;
    } catch (error) {
        console.error("Error:", error);
    }
    return output;
};

let textareaObj = new ej.inputs.SmartTextArea({
    placeholder: 'Enter your queries here',
    floatLabelType: 'Auto',
    resizeMode: 'Both',
    rows: 3,
    cols: 35,
    userRole: 'Employee communicating with internal team',
    UserPhrases: [
        "Please find the attached report.",
        "Let's schedule a meeting to discuss this further.",
        "Can you provide an update on this task?",
        "I appreciate your prompt response.",
        "Let's collaborate on this project to ensure timely delivery."
    ],
    aiSuggestionHandler: serverAIRequest
});
textareaObj.appendTo('#smart-textarea');

const rolesData = [
    "Maintainer of an open-source project replying to GitHub issues",
    "Employee communicating with internal team",
    "Customer support representative responding to customer queries",
    "Sales representative responding to client inquiries"
];

let presets = [
    {
        userRole: "Maintainer of an open-source project replying to GitHub issues",
        userPhrases: [
            "Thank you for contacting us.",
            "To investigate, we'll need a repro as a public Git repo.",
            "Could you please post a screenshot of NEED_INFO?",
            "This sounds like a usage question. This issue tracker is intended for bugs and feature proposals. Unfortunately, we don't have the capacity to answer general usage questions and would recommend StackOverflow for a faster response.",
            "We don't accept ZIP files as repros."
        ]
    },
    {
        userRole: "Customer support representative responding to customer queries",
        userPhrases: [
            "Thank you for reaching out to us.",
            "Can you please provide your order number?",
            "We apologize for the inconvenience.",
            "Our team is looking into this issue and will get back to you shortly.",
            "For urgent matters, please call our support line."
        ]
    },
    {
        userRole: "Employee communicating with internal team",
        userPhrases: [
            "Please find the attached report.",
            "Let's schedule a meeting to discuss this further.",
            "Can you provide an update on this task?",
            "I appreciate your prompt response.",
            "Let's collaborate on this project to ensure timely delivery."
        ]
    },
    {
        userRole: "Sales representative responding to client inquiries",
        userPhrases: [
            "Thank you for your interest in our product.",
            "Can I schedule a demo for you?",
            "Please find the pricing details attached.",
            "Our team is excited to work with you.",
            "Let me know if you have any further questions."
        ]
    }
];

let dropDownPresets = new ej.dropdowns.DropDownList({
    dataSource: rolesData,
    placeholder: "Select a role",
    value: "Maintainer of an open-source project replying to GitHub issues",
    popupHeight: "200px",
    change: (e) => {
        let selectedRole = e.value;
        let selectedPreset = presets.find((preset) => preset.userRole === selectedRole);
        textareaObj.userRole = selectedRole;
        textareaObj.UserPhrases = selectedPreset.userPhrases;
    }
});
dropDownPresets.appendTo('#user-role');
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Essential JS 2 TextArea</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 TextArea Components" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.1.48/ej2-inputs/styles/material.css" rel="stylesheet" />
    <script src="https://cdn.syncfusion.com/ej2/27.1.48/dist/ej2.min.js" type="text/javascript" ></script>
    <script src="../azure_openai.js" type="module"></script>
    <style>
      .content-wrapper {
        margin: 50px auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
      }

      .content-wrapper div.row {
        padding: 7px 0px;
      }

      .example-label {
        width: 29%;
        font-weight: 700;
      }

      .content-wrapper div.api-row {
        margin: 30px 150px;
      }

      .api-property .left-side {
        font-size: 14px;
        padding: 8px;
      }

      .api-property.property-panel-table div.api {
        padding-left: 0px;
      }

      .e-input-group.e-multi-line-input {
        max-width: 100%;
        margin-top: 40px;
      }
    </style>
  <script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

  <body>
    <div id="container">
      <div class="wrap">
        <h2>Syncfusion Smart TextArea</h2>
        <br />
        <br />

        <div class="col-lg-12 control-section" id="default">
          <div class="content-wrapper">
            <div class="example-label">Select a role</div>
            <div id="container" style="width: 430px">
              <input type="text" id="user-role" />
            </div>
            <textarea id="smart-textarea"></textarea>
          </div>
        </div>
      </div>
    </div>

    <script>
      var ele = document.getElementById("container");
      if (ele) {
        ele.style.visibility = "visible";
      }
    </script>
    <script src="index.js" type="text/javascript"></script>
  </body>
</html>
import { AzureOpenAI } from "https://cdn.jsdelivr.net/npm/openai@4.56.0/+esm";
 
//Warning: Do not expose your API key in the client-side code. This is only for demonstration purposes.

// Replace your Azure OpenAI endpoint, apiVersion, deployment and API key here
const endpoint = "AZURE_OPENAI_ENDPOINT";
const apiKey = "AZURE_OPENAI_API_KEY";
const deployment = "DEPLOYMENT_NAME";
const apiVersion = "API_VERSION";
 
const client = new AzureOpenAI({
    endpoint,
    apiKey,
    apiVersion,
    deployment,
    dangerouslyAllowBrowser: true
});
 
window.AzureAIRequest = async function (options) {
    try {
        const result = await client.chat.completions.create({
            messages: options.messages,
            model: "",
            top_p: options.topP,
            temperature: options.temperature,
            max_tokens: options.maxTokens,
            frequency_penalty: options.frequencyPenalty,
            presence_penalty: options.presencePenalty,
            stop: options.stopSequences
        });
        return result.choices[0].message.content;
    } catch (err) {
        console.error("Error occurred:", err);
    }
}
#container {
    visibility: hidden;
}

#loader {
    color: #008cff;
    font-family: 'Helvetica Neue', 'calibiri';
    font-size: 14px;
    height: 40px;
    left: 45%;
    position: absolute;
    top: 45%;
    width: 30%;
}

.wrap {
    box-sizing: border-box;
    margin: 0 auto;
    padding: 30px 10px;
    width: 260px;
}
  • Type ‘To investigate’ to experience instant sentence autocompletion.

Syncfusion Smart TextArea - Output

View Sample in GitHub.