代码之家  ›  专栏  ›  技术社区  ›  lessan

javascript onsubmit在同一个调用中返回两个不同的值

  •  0
  • lessan  · 技术社区  · 9 年前

    验证功能

         function validateForm(){
                    var els;
                    els = document.getElementById('name');
                    if(els.value == ''){
                        console.log(0);
                        alert('Ai uitat sa completezi numele');
                        return false;
                    }
                    els = document.getElementsByClassName('education');
                    [].forEach.call(els, function (el){
                        if(el.value == ''){
                            alert('Ai uitat unul sau mai multe campuri la educatie');
                            console.log(1);
                            return false;
                        }
                    });
                    console.log(2)
                    return false;
                }
    

    表格

    <form onsubmit="return validateForm()" class="form-horizontal" action="{{ URL::to('/admin/people/') }}" method="POST" id="myForm">
    

    我生成了动态html,所以除了服务器端验证之外,我还做了一个javascript验证,这样当页面重新加载时,用户就不会丢失动态生成的html。 控制台中也没有显示错误

    如果它进入第一个If,它在那里只输出0,所以我猜这是由循环引起的?

    2 回复  |  直到 9 年前
        1
  •  1
  •   Matt Spinks    9 年前

    这:

                [].forEach.call(els, function (el){
                    if(el.value == ''){
                        alert('Ai uitat unul sau mai multe campuri la educatie');
                        console.log(1);
                        return false;
                    }
                });
    

    console.log 不管它来自哪个线程。它只是按照接收数据的顺序记录。

        2
  •  0
  •   Nix    9 年前

    这个 return false
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    for (let i = 0, len = els.length; i < len; i++) {
      let el = els[i];
      if(el.value == ''){
        alert('Ai uitat unul sau mai multe campuri la educatie');
        console.log(1);
        return false;
      }
    }