我必须阻止用户在带有knockout的输入类型文本中插入非数字值:
这是我的HTML:
<input data-bind="value: myModel.myNumber, valueUpdate: 'afterkeydown', event: { change: validateMyNumber }" type="number" />
这里是js:
self.validateMyNumber = function (data, event) {
var input = data.myModel.myNumber();
if (input == "")
{
}
};
我找不到写在validateMyNumber函数内部的逻辑...当我按下按钮时,它不是一个数字我在模型中丢失了旧值而且我得到一个空字符串...在textBox没有改变而是...... 我只想要,如果我插入一个非数字值,我必须阻止文本框中的插入...我该怎么办?
答案 0 :(得分:2)
我将此作为输入[type = number]元素的全局规则。你不需要任何具体的淘汰赛。
$(document).on('keypress change focus', 'input[type="number"]', function (e) {
var isKeypress = e.type === 'keypress';
var isChange = e.type === 'change';
var isFocus = e.type === 'focus' || e.type === 'focusin';
var charTyped = String.fromCharCode(e.which);
var $el = $(this);
// store original value to revert change that invalidates min
if (isFocus) {
this.originalVal = $el.val();
return;
}
// block invalid keystrokes
if (isKeypress) {
// don't allow non-numeric chars
if (!/^[\.0-9]$/.test(charTyped)) {
e.preventDefault();
return;
}
// don't allow double periods (123.456.789)
if (charTyped === '.' && $el.val().indexOf('.') > -1) {
e.preventDefault();
return;
}
}
// don't allow >max or <min values
if (isChange) {
var min = $el.attr('min');
var max = $el.attr('max');
var amt = parseInt($el.val() + charTyped);
if (max && amt > max || min && amt < min) {
// revert change
$el.val(this.originalVal);
$el.focus();
}
}
});