具有指定模式的HTML输入

时间:2016-10-19 19:09:39

标签: jquery html knockout.js

我有一个'text'类型的输入文本框。我的要求是这个文本框只能接受数字和小数点[这是可选的]。我不能使用步骤,因为步骤将在数字后命令小数点,因为我有几个我不想使用小数点的情况。 例如,如果基于事务计数的下拉选择,则文本框不应允许输入小数点。 第二个例子,如果我的下拉选择是交易金额,那么文本框应该允许我输入带小数点的输入。

1 个答案:

答案 0 :(得分:0)

小提琴http://jsfiddle.net/LkqTU/32169/

听起来好像你正在寻找淘汰赛延长器 http://knockoutjs.com/documentation/extenders.html

在小提琴中,我基本上通过更改精确值来复制淘汰文档http://jsfiddle.net/LkqTU/32169/中的代码,您可以决定要舍入到的小数位数。

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 model() {
  var self = this;
  myvalue1 = ko.observable('').extend({ numeric: '0' });
  myvalue2 = ko.observable('').extend({ numeric: '2' });
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);

});