make an input only-numeric type on knockout

后端 未结 10 1055
情书的邮戳
情书的邮戳 2020-11-30 06:15

i read many tutorials but i dont know how to do this, this is the input

input(type=\"text\",name=\"price\",id=\"price\"data-bind=\"text: price,valueUpdate:[\         


        
10条回答
  •  心在旅途
    2020-11-30 06:36

    Knockout has extenders for this. Check This from knockoutjs.com explaining how to use observable extenders to force input to be numeric. I paste the code from the documentation here:

    Source code: View

    (round to whole number)

    (round to two decimals)

    Source code: View model

    ko.extenders.numeric = function(target, precision) {
        //create a writable computed observable to intercept writes to our observable
        var result = ko.pureComputed({
            read: target,  //always return the original observables value
            write: function(newValue) {
                var current = target(),
                    roundingMultiplier = Math.pow(10, precision),
                    newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
                    valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
    
                //only write if it changed
                if (valueToWrite !== current) {
                    target(valueToWrite);
                } else {
                    //if the rounded value is the same, but a different value was written, force a notification for the current field
                    if (newValue !== current) {
                        target.notifySubscribers(valueToWrite);
                    }
                }
            }
        }).extend({ notify: 'always' });
    
        //initialize with current value to make sure it is rounded appropriately
        result(target());
    
        //return the new computed observable
        return result;
    };
    
    function AppViewModel(one, two) {
        this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
        this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
    }
    
    ko.applyBindings(new AppViewModel(221.2234, 123.4525));
    

提交回复
热议问题