【问题标题】:jQuery textbox validation using both on keyup and blurjQuery 文本框验证同时使用 keyup 和 blur
【发布时间】:2014-01-27 17:28:25
【问题描述】:

我有一个文本框,需要验证 keyup 和 blur 事件。如果我输入“X”,两个事件都会触发,显然你会看到基于下面代码的两个警报。需要 keyup 事件,因为我可能会根据有效值触发一些操作,并且还需要保留 blur 事件以防按下 Tab 键。目标是在此处显示一个警报。 \m/ \m/

$("#txtLength").on('keyup blur', function (e) {
    if ($(this).val().length > 0) {
        switch (true) {

            case !$.isNumeric($(this).val()):
                alert("Please enter a numeric value.");
                $(this).focus();
                break

            case ($(this).val() < 5) || ($(this).val() > 10):
                alert("Length must be a numeric value between 5 and 10.");
                $(this).focus();
                break;

            default:
        }
    }
});

【问题讨论】:

  • 如果您在 keyup 上进行验证,则不需要在 blur 上进行验证,除非您在 blur 上进行完全不同的操作。
  • 你确实需要它。如果您只使用 keyup 事件,您将收到警报并设置焦点。但是,用户现在可以跳出文本框,留下无效值。
  • 你的陈述在这里是错误的。 如果我输入“X”,两个事件都会触发 jsfiddle.net/EbLdf .. 只有 keyup 事件会被触发。
  • 您想验证 ONKEYPRESSONCHANGE 事件。

标签: jquery validation


【解决方案1】:

感谢您的所有意见。一些好的想法有助于解决问题。坚持使用 .on 按键和模糊来避免显示两个警报的主题,这就是我最终要做的事情。

var bAlertCalled = false;

$("#txtLength").on('keyup blur', function (e) {
    if (bAlertCalled === true) {
        bAlertCalled = false;
        return;
    }

    if ($(this).val().length > 0) {
        var iLength = parseInt($(this).val());

        switch (true) {
            case !$.isNumeric($(this).val()):
                bAlertCalled = true;
                $(this).focus();
                alert("Please enter a numeric value.");
                break

            case (iLength  < 5) || (iLength  > 10):
                bAlertCalled = true;
                $(this).focus();
                alert("Length must be a numeric value between 5 and 10.");
                break;

            default:
        }
    }
});

【讨论】:

    【解决方案2】:

    似乎这只会在您使用 alert() 或其他会打断用户的方法时引起问题。使用一种内联验证形式,用户可能永远不会注意到。此外,您对值的检查不起作用,因为“6”不是 > 5 或

    html:

    <input type="text" id="txtLength" /> <span id='spanLengthValidation'></span>
    

    脚本

    $("#txtLength").on('keyup blur', function (e) {
        $("#spanLengthValidation").text("");
        var amt = parseInt($(this).val())
        if ($(this).val().length > 0) {
            switch (true) {
            case !$.isNumeric($(this).val()):
                $("#spanLengthValidation").text("Please enter a numeric value.");
                $(this).focus();
                break;
    
            case (amt < 5) || (amt > 10):
                $("#spanLengthValidation").text("Length must be a numeric value between 5 and 10.");
                $(this).focus();
                break;
    
            default:
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2013-12-15
      • 2018-02-19
      • 1970-01-01
      • 2017-07-30
      • 2014-05-05
      相关资源
      最近更新 更多