【问题标题】:HTML5 - type="number" prevents non-numbers in Chrome but not in IE & FFHTML5 - type="number" 防止 Chrome 中的非数字,但 IE 和 FF 中没有
【发布时间】:2016-02-18 22:00:55
【问题描述】:

我正在用 MVC 编写一个网站,并且我的表单中有一个价格字段。 我的 Razor 代码如下所示:

@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "myclass", min = 0, max = 1000000 } })

我的 ViewModel 属性如下所示:

[Display(Name = "Price")]
[Range(0, 1000000, ErrorMessage="Please enter a valid Price")]
public int Price { get; set; }

在 Chrome 中,用户不能输入除. 之外的任何其他字符,但在 Firefox 和 Internet Explorer 中可以,这不是我想要的。

HTML5 标准没有扩展到 UI 是否正确? Chrome 是否有奖励?还是应该 IE 和 FF 大写字母(例如 $ 之类的字符)而我做错了什么?

编辑:如果我在 IE 中以 $ 开头输入,它会在失去焦点时使控件空白。在 Firefox 中它仍然存在。

【问题讨论】:

标签: html forms google-chrome internet-explorer firefox


【解决方案1】:

我使用 JQuery 解决了这个问题。这些是步骤:

1) 创建要加载的外部文件 - MyUtils.js

2) 粘贴此 JQuery 代码:

// Use like: $('#SomeId').forceNumeric()
jQuery.fn.forceNumeric = function (intsOnly) {
    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)
        {
            // ints only: look for a decimal. Disallow comma
            // minus and period on keypad
                if ((intsOnly) && (key == 190 || key == 188 || key == 109 || key == 110)) {
                    return false;
            }
                // Input is OKAY
                return true;
            }
        return false;
         });
    });
}

3) 在你要使用这个的页面上,加载js文件 例如脚本 src="/Scripts/MyUtils.js"

4) 将该方法应用于设置字段

$('#Price').forceNumeric(true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-02
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多