您好我有一个输入框:
<input id="txtboxToFilter" type="text" placeholder="dd/mm/yyyy" />
现在我希望它只接受日期格式,所以如果用户试图输入一个字母就不会让他...
我试过这个:
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
但它不起作用......任何想法?
答案 0 :(得分:1)
只接受号码,你可以试试这个
$("#txtboxToFilter").forcenumeric();
$.fn.forcenumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
};
答案 1 :(得分:0)
您可以尝试使用此jquery代码仅输入数字,而不是字符。
DEMO: - http://jsfiddle.net/8z92v8yf/2/
<input id="txtboxToFilter" type="text" placeholder="dd/mm/yyyy" />
<span id="errmsg"></span>
$(document).ready(function () {
//called when key is pressed in textbox
$("#txtboxToFilter").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});