简体   繁体   English

使用jQuery显示错误消息并使其消失

[英]Showing error message using jQuery and making it disappear

Below is a simple jQuery code for showing error messages on submission of form, if the given conditions are not fulfilled. 下面是一个简单的jQuery代码,用于在未满足给定条件的情况下显示提交表单时的错误消息。 This works fine and shows error messages on form submission but I want to change it to keyup function which seems easy, changing $('#submit').click(function() { to $("input").keyup(function(){ works. Now problem is error messages appears on keyup if condition is not fulfilled but does not disappear if condition is fulfilled until I go to next input leaving some error so that inputs error message appears. So what changes I need to make in my code so that error message appearing on keyup disappera as soon as that condition is fulfilled. 这可以正常工作并在提交表单时显示错误消息,但我想将其更改为似乎很简单的keyup函数,将$('#submit').click(function() {更改$("input").keyup(function(){起作用。现在的问题是,如果不满足条件,则错误消息会出现在keyup ,但是如果条件得到满足,错误消息就不会消失,直到我转到下一个输入时,留下了一些错误,以便输入错误消息出现了。代码,以便在满足该条件后立即在keyup disappera上显示错误消息。

<script type="text/javascript">
    $(document).ready(function() {
    $('#submit').click(function() {
         var title = document.getElementById('title').value;
         var category = document.getElementById('category').value;    
         if (category == "") {
          $('#er').html('Oops! Please select a category from the options.');
          return false;
          }
          else if (title == "") {
          $('#er').html('Oops! Title cannot be empty.');
          return false;
          }
          else if (title.length > 100 || title.length < 5) {
          $('#er').html('Oops! Make sure title is 5 to 100 characters long.');
          return false;
         }
       });
     });
</script>

Try to .empty() the error message initially in the event handler, 最初尝试在事件处理程序.empty()错误消息,

 $('input').keyup(function() {     
     var title = document.getElementById('title').value;
     var category = document.getElementById('category').value;
     var error = $('#er').empty();
     if (category == "") {
      error.html('Oops! Please select a category from the options.');
      return false;
      }
      else if (title == "") {
      error.html('Oops! Title cannot be empty.');
      return false;
      }
      else if (title.length > 100 || title.length < 5) {
      error.html('Oops! Make sure title is 5 to 100 characters long.');
      return false;
     }
   });
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM