jQuery限制在Bootstrap输入中键入某些数字 [英] jQuery Restricting certain numbers from being typed in a Bootstrap input
问题描述
好的,我犯了一个错误,盲目地复制并粘贴了一个代码段",该代码段应限制用户在Bootstrap输入字段中键入除数字以外的任何内容.
Okay, I did a mistake and blindly copied and pasted a ''code snippet' that is supposed to restrict the user from typing down ANYTHING ELSE other than a number in a Bootstrap input field.
盲目地这样做,我并没有真正理解它应该如何工作.现在,我需要允许小数点.".键入,我不知道需要更改什么.
By blindly doing that, i did not really understood how it's supposed to work. Now i need to allow the decimal point, the "." to be typed down and i don't know what i need to change.
有人可以解释下面的代码片段或提供资源吗?
Can someone explain the snippet below or provide a resource?
$('#elementXPosition,#elementYPosition,#elementWidth,#elementHeight').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
推荐答案
这是我的解决方案能够为您创建
有两种可能的解决方案,我更愿意使用HTML的pattern
功能.
Here is the solution I am able to create for you
There are two possible solutions to go with and I would prefer to go with HTML's pattern
feature.
**HTML**
<input type="text" id="elementXPosition" pattern="[0-9.]+" title="Please enter decimal numbers only" placeholder="Using pattern" />
<input type="text" id="elementYPosition" placeholder="Using jQuery" />
**jQuery**
$(document).ready(function () {
$("#elementYPosition").keydown(function (e) {
/*To check if shift key was pressed*/
if (e.shiftKey == true) {
e.preventDefault();
}
/*Allows some keys to be pressed*/
if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 46 || e.keyCode == 190) {} else {
e.preventDefault();
}
/*This will allow the '.' to be pressed only once*/
if ($(this).val().indexOf('.') !== -1 && e.keyCode == 190) e.preventDefault();
});
});
这也是密钥代码列表您可能需要根据自己的意愿编辑代码.
希望对您有帮助.
Also here is the list of key codes you might need to edit the code as per your wish.
Hopefully it helps.
这篇关于jQuery限制在Bootstrap输入中键入某些数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!