【问题标题】:jQuery Restricting certain numbers from being typed in a Bootstrap inputjQuery限制在引导输入中输入某些数字
【发布时间】:2014-02-23 09:50:12
【问题描述】:

好的,我犯了一个错误,盲目地复制并粘贴了一个“code sn-p”,它应该限制用户在 Bootstrap 输入字段中输入除数字之外的任何其他内容。

盲目地这样做,我并没有真正理解它应该如何工作。现在我需要允许小数点“。”要输入,我不知道我需要更改什么。

有人可以解释下面的sn-p或提供资源吗?

$('#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();

});

【问题讨论】:

  • @Satpal 他甚至想让.(dot) 写在文本框中,而你建议的重复问题是不同的。
  • @Bhavik,我撤回了近距离投票。但是有足够的材料可用
  • You can use this 作为替代且有效的解决方案,您正在搜索的内容。
  • @Satpal 可能有。我只是没有得到循环的东西

标签: jquery key-bindings


【解决方案1】:

Here is the solution I am able to create for you
有两种可能的解决方案可供使用,我更愿意使用 HTML 的 pattern 功能。

**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();

    });
});  

这里还有the list of key codes,您可能需要根据自己的意愿编辑代码。
希望它有所帮助。

【讨论】:

  • @NicholasKyriakides 很高兴为您提供帮助...!! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多