尝试在没有submit()按钮的情况下添加jQuery验证

时间:2017-10-20 15:44:04

标签: jquery html validation

以下是我的代码。我想要做的是添加验证,以便当用户点击输入字段时,验证消息" name required"出现。然而,在那一刻,它就在输入字段的下方并且始终存在。谢谢



$(document).ready(function(){ 
  if($('#firstname').val() == ''){
    $('.errorMsg').show();
  } else{ 
    $('.errorMsg').hide();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name"     maxlength="15"  <span class="errorMsg">Name required </span>
</input>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

使用CSS最初隐藏错误消息。您还有无效的HTML:错误消息span无法嵌套在输入中。

工作解决方案:

&#13;
&#13;
$(document).ready(function(){ 
  $('#firstname').on('blur', function() {
      if($(this).val() === '') {
        $('.errorMsg').show();
      } else {
        $('.errorMsg').hide();
      }
  });
});
&#13;
.errorMsg {
    display: none;
    color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name" 
 maxlength="15"/>
 <span class="errorMsg">Name required </span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用blur事件:

$(document).ready(function() {
    $('#firstname').on('blur', function() {
        if ($('#firstname').val() == '') {
            $('.errorMsg').show();
        } else {
            $('.errorMsg').hide();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="First name" 
   maxlength="15">  <span class="errorMsg" style="display: none;">Name required </span>
</input>

答案 2 :(得分:0)

使用blur事件,可以使用jQuery直接从找到的元素调用

$(document).ready(function(){

    $('.errorMsg').hide();

    $('#firstname').blur(function(){
    if($('#firstname').val() == ''){
        $('.errorMsg').show();
    }
        else{ 
            $('.errorMsg').hide();
        }

    });


});

这是JSFiddle

答案 3 :(得分:0)

jQuery Blur - 将事件处理程序绑定到“blur”JavaScript事件,或在元素上触发该事件。

尝试(JSFiddle

var firstNameInput = $('input#firstname'),
    errorMsgEl = $('.errorMsg');

// Bind blur on the input for 'first name'
firstNameInput.bind('blur', function () {
    // Check if input is blank
    if(firstNameInput.val() == '') {
        // Ensure error isn't already displayed
        if (errorMsgEl.length == 0) $("<div class='errorMsg'>Name required</div>").insertAfter(this);
    } else {
        errorMsgEl.remove();
    }
});