验证失败时,每个新提交的我都会收到越来越多的警报

我在html中有4个输入框,我想检查其中一个还是多个为空。这段代码的问题是,当检查失败时,在每个新提交时,我都会收到递增数量的警报。意思是,如果第一次验证Value2失败,我收到1条警报,那么我插入了一个正确的Value2,但Value3错误,因此,对于Value3仅显示一个警报,我收到了一堆2条警报,依此类推。 。

<script>
    function onSubmitNotification() {
        var checkThisOnes = ["Value1", "Value2", "Value3", "Value4"];
        $('#myform').submit(function() {
            for (i = 0; i < checkThisOnes.length; i = i + 1) {
                var checkedValue = $('#'+checkThisOnes[i]).val();
                if (checkedValue === undefined || checkedValue === "") {
                    alert("This field is empty: " + checkThisOnes[i])
                    return false
                }
            }
        });
</script>
评论
  • 客官,不要
    客官,不要 回复

    use event.preventDefault() on submit. This will stop default submit behavior.

    $('#myform').submit(function(event) {
       event.preventDefault()
       // .. rest of the code
    
      if(formvalid){ 
       // submit again
        $('#myform').submit()
      }
    })
    
  • oalias
    oalias 回复

    I don't know why you need to use onSubmitNotification() but without that also it will work .Also,remove return false and use e.preventDefault() to avoid default submission.

    演示代码:

    var checkThisOnes = ["Value1", "Value2", "Value3", "Value4"];
    $('#myform').submit(function(e) {
      e.preventDefault();
    
      for (i = 0; i < checkThisOnes.length; i = i + 1) {
        var checkedValue = $('#' + checkThisOnes[i]).val();
        if (checkedValue === undefined || checkedValue === "") {
          alert("This field is empty: " + checkThisOnes[i])
    
        }
    
      }
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    <form id="myform">
      <input type="text" id="Value1">
      <input type="text" id="Value2">
      <input type="text" id="Value3">
      <input type="text" id="Value4">
      <button type="submit">Submit</button>
    </form>