EBOI
9/29/2017 - 8:27 AM

Obsługa wartości liczbowych - argument jako ilość miejsc po przecinku

Obsługa wartości liczbowych - argument jako ilość miejsc po przecinku

ko.bindingHandlers.numeric = {
    init: function (element, valueAccessor) {
        $(element).on("keydown", function (event) {
            // Allow: backspace, delete, tab, escape, and enter
            if (event.keyCode === 46 || event.keyCode === 8 || event.keyCode === 9 || event.keyCode === 27 || event.keyCode === 13 ||
                // Allow: Ctrl+A
                (event.keyCode === 65 && event.ctrlKey === true) ||
                // Allow: , for decimal and prevent if already exist
                (event.key === "," && $(this).val().length > 0 && $(this).val().indexOf(",") === -1) ||
                // Allow: - - if phone number
                (element.type === "tel" && (event.keyCode === 109 || event.keyCode === 189)) ||
                // Allow: home, end, left, right
                (event.keyCode >= 35 && event.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            } else {
                // Ensure that it is a number and stop the keypress
                if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
            }
        });

        if (valueAccessor() !== null) {
            $(element).on("focus",
                function() {
                    if ($(this).context.value === "0")
                        $(this).context.value = "";
                });

            $(element).on("blur",
                function() {
                    if ($(this).context.value === "")
                        $(this).context.value = "0";
                });
        }
    },
    update: function (element, valueAccessor, allBindings) {
        allBindings().value.extend({ numeric: valueAccessor() });
    }
};
<input data-bind="value: Field, numeric: 2" />