选择"全部" if / else语句之前的类元素

时间:2017-05-25 15:49:52

标签: javascript

我在开始使用Googles reCAPTCHA之前正在制定一个字段验证条款,而且我遇到了一些问题。

我可以检查一个元素是否有一个ID的值,但我似乎无法通过CLASS工作。如果填写了REQUIRED类的所有字段,我基本上想要执行recaptcha。

按ID,这仅适用于一个问题。

function validate(event) {
event.preventDefault();
if (!document.getElementById('q1').value) {
    alert("You must enter text into the required fields!");
} else {
    grecaptcha.execute();
}

按CLASS,不工作:(

function validate(event) {
event.preventDefault();
var questions = document.getElementsByClassName('required');
for (var i=0; i<questions.length; i++) {
    if (questions[i].value) {
        alert("You must enter text into the required fields!"); 
    } else {
        grecaptcha.execute();
    }
}

我之前从未做过这样的事情,所以我们将非常感谢您对解决方案的任何见解。

干杯。

2 个答案:

答案 0 :(得分:2)

两个问题:

  1. 您正在为每个有效字段重复调用grecaptcha.execute 一次(即使其他字段无效)。

  2. 你正在检查questions[i].value,如果空白和真空不是空白,那将是假的,但后来将真理视为空白。

  3. 相反,只需记住您是否找到了任何无效的错误,然后发出错误或执行错误(并将!添加到支票中):

    var questions = document.getElementsByClassName('required');
    var valid = true;
    for (var i=0; valid && i<questions.length; i++) {
        if (!questions[i].value) {
            valid = false;
        }
    }
    if (valid) {
        grecaptcha.execute();
    } else {
        alert("You must enter text into the required fields!"); 
    }
    

    附注:您当前检查空字段将接受仅包含空格的字段。如果你想要将它们除去,请使用trim(在任何模糊的现代浏览器上,你可以将它填充为过时的IE8):

    if (!questions[i].value.trim()) {
    

答案 1 :(得分:1)

如果一个元素是正确的,它将执行recaptcha。您想检查所有是否正确:

function validate(event) {
    event.preventDefault();
    var questions = document.getElementsByClassName('required');
    for (var i=0; i<questions.length; i++) {
        if (questions[i].value && question[i].value!=="") {
           return alert("You must enter text into the required fields!"); 
        } 
    }
    grecaptcha.execute();
}