【问题标题】:HTML input with specified pattern具有指定模式的 HTML 输入
【发布时间】:2016-10-20 19:17:15
【问题描述】:

我有一个“文本”类型的输入文本框。我的要求是这个文本框只能接受数字和小数点[这是可选的]。我不能使用 step 因为 step 将要求数字后的小数点,因为我很少有不想使用小数点的场景。 例如,如果我的下拉选择基于事务计数,则文本框不应允许输入小数点。 第二个例子,如果我的下拉选择是交易金额,那么文本框应该允许我输入带小数点的输入。

【问题讨论】:

标签: jquery html knockout.js


【解决方案1】:

小提琴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);

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多