"Determine the total count of letters and numbers entered in a textarea and display the result without using jQuery

I am currently utilizing Bootstrap and the CKEditor5 Classic.

I am looking to implement a character counter using ONKEYUP in my textarea that displays each time a key is released within div id countThis.

I specifically require a solution using pure JavaScript, as I have attempted the following without success.

How can I successfully achieve this? Thank you for your help!

(Please note that jQuery should not be used!)

CODE

<div class="row">
  <div class="form-group col-10">
    <label class="form-label" for="txt">Description</label>

    <textarea id="txt" class="form-control" onkeyup="CheckInput()"></textarea>

  </div>
  <div class="col-2 mt-4" id="countThis"></div>
</div>
ClassicEditor
  .create(document.querySelector('#txt'))
  .catch(error => {
    console.error(error);
  });

function CheckInput() {
  var value = document.getElementById("txt").value.length;
  console.log(value); // NO OUTPUT HERE
  document.getElementById("countThis").innerHTML = value;
}

Answer №1

If you want to efficiently capture the event, I recommend using the CKEditor API instead of relying on the keyup attribute. Here's how you can implement it:

ClassicEditor
    .create(document.querySelector('#txt'))
    .then(editor => {
        /// Set up change listener
        editor.model.document.on( 'change:data', () => {  /// <--- Implementing Changes listener

            /* ALL THE LOGIC GOES HERE */

            document.getElementById("countThis").innerHTML = 
                editor    /// <--- Referencing Editor
                    .getData()    /// <--- Editor Content
                    .replace(/<[^>]*>/g, '')    /// <--- Converting HTML to plain text
                    .replace('&nbsp;', ' ')    /// <--- Removing &nbsp; for spaces
                    .length;    /// <--- Getting plain text length
        });
    })
  .catch(error => {
    console.error(error);
  });
<script src="https://cdn.ckeditor.com/ckeditor5/30.0.0/classic/ckeditor.js"></script>
<div class="row">
  <div class="form-group col-10">
    <label class="form-label" for="txt">Description</label>

    <textarea id="txt" class="form-control"></textarea>

  </div>
  <div class="col-2 mt-4" id="countThis"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Check if a Discord.js bot responds based on whether a user holds a designated role

I'm looking to make my bot respond to a specific role. If the user does not have that role, I want the bot to reply with a message saying "You are not allowed to perform this command." Here is the code snippet I am using: client.on("message", (message ...

Access the input field value with PHP and store it in a variable

I previously looked into this issue, but the solution provided in the accepted answer did not resolve it for me: How to get input field value using PHP Below is an excerpt from my result.php file: ... <th> <form name="form" action= ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Find the nearest locations in an Array

My document is quite straightforward, containing 3 location objects within an array. Data: { "_id" : ObjectId("57c3c479a306b3613cf1ee5b"), "location_history" : [ { "location_name" : "Area 1", "date" : 1472447609, ...

Is there a specific event in fancytree that is triggered once the tree data has finished loading entirely?

Is there a way to determine when fancytree has finished loading data and the component is fully loaded in order to change its options? I am currently attempting to change the selectMode (for example, from 3 to 2), but the data is not being fully loaded a ...

Assign the JSON data to a variable

Can someone help me figure out how to save a JSON file from a URL in a variable and then work with it? Normally, it looks something like this: var jsonOriginal = { name: "Steve", age: 27, jobTitle: "Program Manager" }; alert(person.name); But now I need ...

Tips for displaying tooltips with values that are constantly updating

I am seeking a solution to display tooltips when hovering over a textarea with changing values. The user has the ability to input lengthy text, and I would like the tooltip to show the updated data. Any suggestions on how this can be achieved? ...

Capturing jQuery ajax requests in Angular

Within my Angular application, I am utilizing the integrated $.couch API from CouchDB. My goal is to intercept every ajax request, regardless of whether it originates from Angular's $http service or jQuery's $.ajax (which is utilized by $.couch). ...

Is there a way to execute code after completion of all threads?

I've developed a multi-threaded web crawler that downloads a website and stores it in a database, however, this process takes around 4 minutes. In an attempt to speed up the crawling process, I implemented the node.js cluster module. Yet, I'm fac ...

The HTML document is unable to locate the Angular framework

I'm encountering an issue with the code below on my HTML page - every time I run it, I receive an error message saying "angular is not defined". I've already included angular in the head section of the page so I'm puzzled as to why it's ...

What is the best way to maintain an ongoing sum of multiple values using bacon.js?

Experimenting with the power of bacon.js. I want to maintain a dynamic total of values from a set of text inputs. The example on the github page utilizes the .scan method along with an adding function, which functions well for simple increment and decremen ...

A JavaScript function for flattening objects within nested objects and arrays recursively

I have a large JSON object that may be irregular, and I am looking for a solution to flatten all of its objects into a single array. Here is an example JSON: { "name":"getPost", "request":{ "type":"object", "fields":[{ ...

Arranging numbers in JavaScript lists

empList = [ { "Account": "AAA - 0029", "Available": "$100" }, { "Account": "BBB- 0146", "Available": "200" }, { "Account": "AAA - 1812", "Available": "300"}, { "Account": "CCC- 2019", "Available": "400"}, { "Account" ...

Utilizing promises to recursively modify a set of objects within an express router in node.js: A step-by-step guide

I am in the process of creating an array of node objects, each with a unique label and children nodes identified by their own unique labels. This data structure will be utilized in conjunction with a tree component on my frontend (). A Category represents ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

What causes addEventListener to not return a value?

In this snippet of code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false)); After using console.log(), the output is undefined. The purpose of rockBtn:const rockBtn = document.querySelecto ...

When dispatching an action through redux, the component replicates itself

After writing code to display a chart and implementing a function to change its timeframe, an unexpected issue arose - a duplicate chart appeared when the function was triggered. Included below is the Chart.js code snippet: let chartProperties = { wid ...

Adjusting image dimensions dynamically using JavaScript based on screen size

My bootstrap setup seems to be causing issues when using the @media (min-height: 1000px) rule as the image class does not respond as expected. I am looking to implement a JavaScript solution that will automatically resize images once the screen height exc ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

What is the method to obtain the selector string for an HTML node element?

Essentially, my goal is to extract the selector string from an HTML element. Specifically, I want to start with the HTML element and retrieve its selector string (for example: button#myButton) function onclicked(e){ console.log(e.target); // This returns ...