Search code examples
javascriptstringwidgetautofillodoo-13

Create a Widget with the function of auto populate commas or dots into float field (Odoo 13)


I'm trying to create a Widget with the function of auto populate commas or dots when the user enters values into the float field by js.

If the user enters 123456789 , it should automatically become 12,345,667.89 immediately.

But In my code, it just works after click a Button:

odoo.define('autofill.separate', function (require) {
"use strict";

var basic_fields = require('web.basic_fields');
var registry = require('web.field_registry');

var BoldWidget = basic_fields.FieldChar.extend({
    _renderReadonly: function () {
        this._super();
        var old_html_render = this.$el.html();
        var new_html_render = old_html_render.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

        
        this.$el.html(new_html_render);
    },
});

registry.add('autofill_separate', BoldWidget);
});

Please help!

Thank you!


Solution

  • you can use jquery mask plugin:

    1. add this to your backend assets https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js

    2. update your widget:

       var basic_fields = require('web.basic_fields');
       var registry = require('web.field_registry');
      
       var BoldWidget = basic_fields.FieldMonetary.extend({
      
           _prepareInput: function ($input) {
               this._super.apply(this, arguments);
               this.$input.mask("#,##0.00", {reverse: true});
               return this.$input;
           },
      
       });
       registry.add('autofill_separate', BoldWidget);