【问题标题】:How to display an error message for only focused field?如何仅显示焦点字段的错误消息?
【发布时间】:2014-02-12 10:05:52
【问题描述】:

我有 2 个文本框; tb1 和 tb2 .on load ,焦点在 tb1 .. 保存按钮上 tb1 和 tb2 是空的...我只想显示 tb1 错误信息 ...

这是我的代码

$('#btn_SaveCategory').click(function () {

                var uname = $('#txt_CategoryName').val();
                var Description = $('#txt_CategoryDesc').val();

                if (uname == '') {
                    alert("Please Enter Category Name");
                    $('#txt_CategoryName').focus();
                }

                if (Description == '') {
                    alert("Please Enter Category Description");
                }


            });

我尝试搜索但找到了相反的链接 :jQuery validate only validates one field

如果我遗漏了什么,请提出建议

【问题讨论】:

    标签: jquery asp.net .net


    【解决方案1】:

    试试这个。

    演示http://jsfiddle.net/7LRCs/

    $('#btn_SaveCategory').click(function () {
        var uname = $('#txt_CategoryName').val();
        var Description = $('#txt_CategoryDesc').val();
    
        if (uname == '') {
            alert("Please Enter Category Name");
            $('#txt_CategoryName').focus();
        }
        else if (Description == '') {
            alert("Please Enter Category Description");
            $('#txt_CategoryDesc').focus();
        }
    });
    

    【讨论】:

      【解决方案2】:

      您可以像这样使用if else if

      $('#btn_SaveCategory').click(function () {
        var uname = $('#txt_CategoryName').val();
        var Description = $('#txt_CategoryDesc').val();
      
        if (uname == '') {
           alert("Please Enter Category Name");
           $('#txt_CategoryName').focus();
        }
        else if (Description == '') {
           alert("Please Enter Category Description");
           $('#txt_CategoryDesc').focus();
        }
      });
      

      或者您可以在检查下一个条件之前return 函数。像这样

      $('#btn_SaveCategory').click(function () {
      
          var uname = $('#txt_CategoryName').val();
          var Description = $('#txt_CategoryDesc').val();
          if (uname == '') {
             alert("Please Enter Category Name");
              $('#txt_CategoryName').focus();
              return false;
          }
          if (Description == '') {
             alert("Please Enter Category Description");
             $('#txt_CategoryDesc').focus();
             return false;
          }
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-03
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        相关资源
        最近更新 更多