Codemirror's MaxLength Feature

Hello, I am looking for a way to limit the number of characters in CodeMirror v5.5.0. I attempted the following method:

Code:

CMUtils.limitCharacters = function(cm, change) {
    var maxLength = cm.getOption("maxLength");
    if (maxLength && change.update) {
        var str = change.text.join("\n");
        var delta = str.length - (cm.indexFromPos(change.to) - cm.indexFromPos(change.from));
        if (delta <= 0) { return true; }
        delta = cm.getValue().length + delta - maxLength;
        if (delta > 0) {
            str = str.substr(0, str.length - delta);
            change.update(change.from, change.to, str.split("\n"));
        }
    }
    return true;
}

html_editor.on("beforeChange", CMUtils.limitCharacters);
css_editor.on("beforeChange", CMUtils.limitCharacters);
js_editor.on("beforeChange", CMUtils.limitCharacters);

Unfortunately, it did not work as expected.

P.S: I have included maxLength in my code

var html_editor = CodeMirror.fromTextArea(document.getElementById("html"), {
    lineNumbers: true,
    indentWithTabs: false,
    indentUnit: 2,
    autoCloseTags: true,
    theme: 'dracula',
    maxLength: 25,
    mode: {
        htmlMode: true,
        name: "xml"
    }
});

UPDATE 1: I am receiving an error in the console stating that CMUtils is undefined. How can I define it?

Answer №1

It seems that CMUtils was originally created by gskinner for his own projects. The function can be used in different ways, depending on how you want to scope it.

If you choose to use the function as it is currently written, make sure to include the following code snippet at the beginning:

window.CMUtils = window.CMUtils || {};

CMUtils.enforceMaxLength = function(cm, change) { //.....

Alternatively, if you prefer to keep the function private, modify the first line like this:

var enforceMaxLength = function(cm, change) {

Remember to set the option "maxLength" on the CodeMirror editor

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

Minicart.js - Products successfully added to cart but cart fails to appear on screen

Currently, I am facing an issue with my button click function that is supposed to add an item to the cart using the Minicart.js library from minicartjs.com. Although items are successfully being added to the cart upon clicking the button, the cart itself i ...

Using jQuery AJAX to add to a JSON response with the value "d:null"

Hey everyone, I'm encountering a strange issue with my callback function when using the AJAX POST method to call my webservice. The JSON response from the webservice looks like this: Dim ser As New System.Web.Script.Serialization.JavaScriptSerialize ...

How come my product details page keeps automatically scrolling to the bottom every time I visit it?

I am facing an issue where clicking on a card to navigate to the product details page automatically takes me to the bottom of the next page without scrolling. Below is a snippet of my code: import React from "react"; import { Link } from "re ...

The result of using `path.dirname()` on a Windows path will simply return a period

While developing a Vue JS application within electron JS, I encountered an issue specific to Windows operating systems. It seems that the path.dirname() function is returning just a dot . instead of the expected directory path on Unix systems. For example ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

Can a javascript file be included through a symbolic link?

I am working on a PHP web application and I have a question: Is it advisable to store my JavaScript files in the private directory? If yes, can I include them from a symbolic link located in the public directory? ...

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Turf JS is not effectively generating Objects

Exploring the functionality of the helper function called turf.point() const feature = turfHelpers.point(coords, properties, { id: properties.id }); The structure of the variable properties is as follows: properties = { id: 1, thisWorks: 'no pr ...

Choosing the attribute value using jQuery/CSS

Looking for a way to retrieve attribute value using jQuery/CSS <dt onclick="GomageNavigation.navigationOpenFilter('price-left');"> I tried using $("dt[onclick='GomageNavigation.navigationOpenFilter('price-left')']") bu ...

Automated web browser capture downloading feature

Currently, I am in the process of developing a tool to streamline tasks at my workplace. One feature we need is an aspx webpage where users can input information, then click on a submit button. When the submit button is clicked, a javascript download dialo ...

Is Jade used for making subsequent lines children of an included partial?

Recently, I've encountered an issue with a basic jade layout. Here is an example: include test.jade #bar hi In the test.jade file: #foo hello No matter what I try, the #bar element always ends up as a child of #foo. <div id="foo">hello &l ...

Error: The function preciseDiff is not recognized by moment

Encountering an error message: "TypeError: moment.preciseDiff is not a function. I am facing the same issue, wondering if there is a solution or alternative available. I have version 2.24.0 of moment installed. moment-precise-range-plugin In addition, I ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Angular leveraging InnerHTML to distinguish between href and routerLink

Currently facing a challenge where I am dealing with receiving a link from a CMS. This link could be either internal or external to my Angular application. To tackle this, I have implemented logic to differentiate between internal and external links, and t ...

Is there a way to achieve RSA key pair encryption/decryption in Ruby and JavaScript?

I have been experimenting with encrypting data in Ruby using OpenSSL and decrypting it in JavaScript using the JavaScript Forge library. Although the method of distributing keys is functional for research purposes, I am encountering an issue where encrypt ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. https://i.sstatic.net/MtO8l.png In contrast, highlighted near the red arrows i ...

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...