I discovered an issue in Handsontable while trying to copy and paste a numeric value in German format

For my upcoming project, I am looking to incorporate the Handsontable JavaScript grid framework. However, I have encountered a small bug that is hindering me from utilizing this library to its fullest potential.

The task at hand involves displaying a table with German prices, formatted as "18,50 €". In the German language, the comma serves as the decimal point. The default configuration of Handsontable only includes the English language option for the embedded "numeral.js" helper library. To address this, I added the German (de) language definition for numeral.js. By defining the cell format as "0.00 $", I successfully displayed prices correctly as "18,50 €" within the grid.

However, an issue arises when selecting a cell with a value like "1,50 €" by clicking on it, then copying ("Ctrl+C") and pasting ("Ctrl+V") into another cell. The pasted value turns out incorrect as "15,00 €". This discrepancy occurs because the copied value in the clipboard is represented as "1.5" and is interpreted incorrectly upon pasting.

I've included the necessary HTML and JavaScript code snippets below:

<div id="exampleGrid"></div>

Javascript:

(function () {
    var language = {
        delimiters: {
            thousands: '.',
            decimal: ','
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            return '.';
        },
        currency: {
            symbol: '€'
        }
    };
    if (typeof window !== 'undefined' && this.numeral && this.numeral.language)  {
        this.numeral.language('de', language);
    }
}());

$("#exampleGrid").handsontable({
    data: [ [1.5], [] ],
    rowHeaders: true,
    colHeaders: true,
    columns: [
        { type: 'numeric', format: '0.00 $', language: 'de'}
    ]
});

To further illustrate the problem, I've created a jsfiddle demonstration: http://jsfiddle.net/hU6Kz/4873/

Despite working with version 0.23.0, my attempts to work around this bug using hooks and custom validators have been unsuccessful. These approaches failed to provide the original value "1.5" within event callbacks, instead returning the erroneous value "15". Even employing the "beforeChange" hook within the handsontable constructor did not yield the desired result:

beforeChange: function (changes, source) {
        for (var i = changes.length - 1; i >= 0; i--) {
            console.log('Changes: source:' + source + ' row:' + changes[i][0] + ' col:' + changes[i][1] + ' old:' + changes[i][2] + ' new:' + changes[i][3]);
        }
    }

Upon performing the copy and paste action of "1,50 €," the console output displays:

Changes: source:paste row:1 col:0 old:null new:15

In analyzing the source code, I identified the 'validateChanges' function which contributes to the issue:

if (numeral.validate(changes[i][3])) {
    changes[i][3] = numeral().unformat(changes[i][3]);
}

Executing this code with the current numeral language set as 'de' results in "15." Hence, it becomes apparent why the original copied value isn't captured accurately during the "beforeChange" hook trigger.

Moving forward, resolving this challenge poses a question mark. How can we tackle this dilemma effectively?

Update:

Further exploration reveals the impact of 'validateChanges' where:

numeral().unformat('1.5 €')

This operation confirms the derivation of "15" under the 'de' numeral language setting. As such, the timing of 'validateChanges' preceding the invocation of the hook 'beforeChange' underscores the root cause of the issue.

Now, what are the next steps to navigate through this obstacle?

Answer №1

Modification needed in the code at line 24646:

if (languages[currentLanguage].delimiters.decimal !== '.') {
  string = string.replace(/\./g, '').replace(languages[currentLanguage].delimiters.decimal, '.');
}

Replace it with:

if (languages[currentLanguage].delimiters.decimal !== '.') {
  string = string.replace(languages[currentLanguage].delimiters.decimal, '.');
}

The first string replacement function eliminates the decimal point from the original data.

Please be aware that I have limited knowledge about this specific JavaScript library, and altering the code may have unintended consequences. It is recommended to consult the project maintainers on their GitHub page before proceeding.

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

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

When the menu active item is clicked, the header will automatically scroll to the top

I've implemented a sticky header using CSS and JavaScript along with a mega menu. However, I've encountered an issue where when scrolling to the bottom and clicking on the "more" link in the dropdown, the page scrolls back to the top. This is the ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

Increase performance by minimizing unnecessary component re-renders in Next.js using memoization

I am currently exploring the behavior of React within Next.js. I have an index.js page that displays one component Homecard three times and a button that increments a value. Each time I click on the button, all Homecard components are re-rendered. index. ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...

What criteria should I consider when selecting a JavaScript dependency framework?

When it comes to installing dependencies, how do I determine whether to use NPM or Bower? For example, what distinguishes npm install requirejs --save-dev from bower install requirejs --save-dev? Is there a recommended method, or any guidelines for makin ...

Guide to incorporating third-party JavaScript files and functions into my Angular web app

I have been trying to integrate external code (HTML, JS, and CSS files) into my Angular web application. Within this external code, the structure of the HTML file is as follows: index.html <html> <header> </header> <body> </bo ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

What is the mechanism behind the operation of the inherits feature in Node.js?

The following code snippet illustrates how the inherits function works in node.js: exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, ...

Adding double quotes, where they haven't been added yet

I am trying to work with the following string (Very strong=="Very strong"?100:(Very strong=="Above Average"?75:(Very strong=="Average"?50:(Very strong=="Below Average"?25:(Very strong=="Cannot determine"?0:(Very strong=="Poor"?0:0)))))) My desired outpu ...

Verify if the user is currently active

Is there a method to determine if the user is not active? I am currently utilizing raw PHP. I would like for the user to be automatically logged out once they close the window, indicating their inactivity. I attempted implementing window.addEventListener ...

When encountering a 404 redirect, CSS and JS files may fail to display

I created a unique error message using .htaccess, incorporating CSS and JS in separate folders. Although it functions properly when accessed directly, integrating these resources into the 404 Error message results in only the HTML text being displayed with ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

modifying the identification value in HTML and then reverting it

Although this may seem like messy code, I'm really in need of assistance with a problem that has stumped me. Currently, I am working on an E-shop project where I have modals for displaying products. Within these modals, there is a button that allows u ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...