0

我在 MVC 视图上有几个输入字段,我只想允许输入字母 Y 或 N。

当我使用 Firefox(当前版本为 23.0.1)进入这些字段时,该字段的值会突出显示,我可以输入允许的字符,基本上会覆盖该值。例如,如果输入的值为 N,则 N 会突出显示,然后我可以按 Y,N 会被 Y 替换。万岁!

但是,当我使用 Chrome 或 IE(10) 时,该字段会突出显示,但允许的键不会覆盖输入框中的值。该字段取消突出显示,光标位于值的末尾。嘘!

我错过了什么?

//Keydown and blur events for textboxes that only allow Y, or N
$(".onlyYN").keydown(function (e) {
    if (e.keyCode === 89 ||
        e.keyCode === 8 ||
        e.keyCode === 9 ||
        e.keyCode === 78 ||
        e.keyCode === 13 ||
        e.keyCode === 46 ||
        e.keyCode === 16) {
        clearError(this);
        setControlValueToUpperCase(this);
        return;
    }
    markControlAsWarning(this);
    alertify.log("The " + $(this).attr('id') + " field only accepts the single characters 'Y' or 'N'");
    e.preventDefault();
}).blur(function () {
    if ($(this).val().toUpperCase() !== "Y" && $(this).val().toUpperCase() !== "N") {
        markControlAsError(this);
        alertify.error("The " + $(this).attr('id') + " field only accepts the single characters 'Y' or 'N'");
        return;
    }
    clearError(this);
    setControlValueToUpperCase(this);
});
4

1 回答 1

0

好吧,我似乎过早地使用了 setControlValueToUpperCase() 方法。因此,首先将我的 keydown 语句更改为

if (e.keyCode === 89 ||
        e.keyCode === 8 ||
        e.keyCode === 9 ||
        e.keyCode === 78 ||
        e.keyCode === 13 ||
        e.keyCode === 46 ||
        e.keyCode === 16) {
        clearError(this);
        return;
    }

解决了我的问题。

function setControlValueToUpperCase(ctrl) {
    /// <summary>
    ///     Set the contents of the control value to upper case
    /// </summary>
    /// <param name="ctrl">The control reference which contains value</param>
    $(ctrl).val($(ctrl).val().toUpperCase());
}

万岁我!!

于 2013-08-28T15:57:35.993 回答