Editing percentage values with a KendoUI NumericTextBox

by Michael Henstock 16. April 2013 23:48

KendoUI has some great widgets and functionality built into it, and while it's not the best library in every situation it's great in most situations. The numeric text box widget is a simple widget that I'm using more frequently for percentages, which is great, however our users are wanting something that the default functionality doesn't supply. Our users love the widget but want to edit the text with the whole numbers (5 for 5% instead of 0.05).

We achieved this by extending the MVVM functionality to include a new formatter in the KendoUI binders. The default binder looks something like this:

<input data-role="numerictextbox" data-format="p" data-bind="value: percent" />

Which shows the value as a whole percentage, and edits in the decimal place number.

By extending the KendoUI binders with the following:

kendo.data.binders.widget.percentage = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);

        var that = this;
        that.element.options.format = "#.00 \\%";
        that.element.options.min = that.element.options.min || 0;
        that.element.options.max = that.element.options.max || 100;

        that.element.element.on("change", function () {
            that.change();
        });
    },
    refresh: function () {
        var that = this,
            value = that.bindings["percentage"].get();

        // Take a percentage value and display it in a simpler percentage format
        that.element.value(value * 100);
    },
    change: function () {
        var value = this.element.value();
        if (!isNaN(value)) {
            // divide the percentage value by 100 to set the model value to the database percentage value
            this.bindings["percentage"].set(value / 100);
        }
    }
});

we can change our input binding to this:

<input data-role="numerictextbox" data-bind="percentage: percent" />

and get the same functionality and the ability to edit the percentages as whole numbers.

You can see a demonstration of this here: http://jsbin.com/ekovif/1/edit

Tags:

JavaScript | KendoUI