JQuery循环遍历元素并返回False如果全部为空

时间:2014-06-27 19:28:19

标签: jquery html loops

如何遍历某个类名的所有元素,并且只有在每个元素都没有值/为null时才返回false?

我知道我可以增加一个int,或者添加一个字符串,或者做类似的事情来测试循环结束后每个字段是否为空但这看起来非常不可持续,更不用说一个可怕的方法了做到这一点。

目前我有我的JS文件:

function verifyPositions() {
  $(".position").each(function () {
    if ($(this).val() == "") {

    }
  });
}

对于我的HTML:

<div class="spacing">
  <a class="applicationLabel">Position(s) interested in:</a><br>
  <input class="position" name="position[]" value="Project Manager" type="checkbox" /> Project Manager<br>
  <input class="position" name="position[]" value="Content Developer" type="checkbox" /> Content Developer<br>
  <input class="position" name="position[]" value="Graphic Designer" type="checkbox" /> Graphic Designer<br>
  <input class="position" name="position[]" value="Digital Media Creator & Storyteller" type="checkbox" /> Digital Media Creator & Storyteller<br>
  <input class="position" name="position[]" value="Programmer" type="checkbox" /> Programmer<br>
  <input class="position" name="position[]" value="Server Engineer/Technician" type="checkbox" /> Server Engineer/Technician<br>
  <input class="position" name="position[]" value="User Experience Designer" type="checkbox" /> User Experience Designer<br>
</div>

编辑:修复

function verifyPositions() {
var flag = false;

$(".position").each(function () {
    if ($(this).prop('checked')) {
        flag = true;
    }
});

if (!flag) {
    return false;
} else {
    return true;
}
}

3 个答案:

答案 0 :(得分:0)

function verifyPositions() {
    $(".position").each(function () {
        if ($(this).val() !== "") {
            return true;
        }
    });
    return false;
}

答案 1 :(得分:0)

我误解了这个问题,并以不同的方式思考它。如果您只想在没有选中复选框的情况下返回false,那么您可以使用:

return $('input[type=checkbox]:checked').length != 0;

如果你想确保选中所有复选框,我将离开以下代表后代。

以下内容将告诉您是否选中了所有复选框:

return $('input[type=checkbox]:checked').length == $('input[type=checkbox]').length;

如果您只关注要检查的特定区域中的所有复选框(例如<div class='spacing'>),则可以使用:

return $('div.spacing input[type=checkbox]:checked').length == $('div.spacing input[type=checkbox]').length;

答案 2 :(得分:0)

修正了它:

function verifyPositions() {
var flag = false;

$(".position").each(function () {
    if ($(this).prop('checked')) {
        flag = true;
    }
});

if (!flag) {
    return false;
} else {
    return true;
}
}