当复选框被选中时,从标签中删除class

When a checkbox becomes checked, remove class from labels

本文关键字:标签 删除 class 复选框      更新时间:2023-09-26

我已经编写了一个基本的表单验证脚本,现在我正试图重置如果用户不填写所需字段时发生的错误。

对于复选框和单选按钮,我已经将类error添加到它们的标签中。它的HTML代码看起来像这样:

<input class="required" id="Example31" name="Example3" type="checkbox" />
<label for="Example31" class="error">Example Input 3 Option 1</label>
<input class="required" id="Example32" name="Example3" type="checkbox" />
<label for="Example32" class="error">Example Input 3 Option 2</label>
<input class="required" id="Example4" name="Example4" type="radio" />
<label for="Example4" class="error">Example Input 4</label>

为了添加错误,我使用以下脚本确定是否选中了具有相同名称的复选框:

$("input.required").each(function() {
    // check checkboxes and radio buttons
        if ($(this).is(":checkbox") || $(this).is(":radio")) {
            var inputName = $(this).attr("name");
            if (!$("input[name=" + inputName + "]").is(":checked")) {
                var inputId = $(this).attr("id");
                $("label[for=" + inputId + "]").addClass("error");
                error = true;
            };
        };
    // end checkboxes and radio buttons
});

如何在不修改HTML的情况下删除错误?我脑子一片空白。我是这么想的:

  1. 找出与每个有错误的标签相关联的名称
  2. 查找具有该ID的复选框或单选按钮
  3. 找出复选框或单选按钮名称
  4. 查找其余同名的复选框或单选按钮
  5. 查找这些输入id
  6. 查找具有这些名称的标签
  7. 清除这些标签的错误

虽然我很失落。如果有人能帮忙的话,我将不胜感激。

我自己解决了这个问题:

$("input.required").each(function() {
    if ($(this).is(":checkbox") || $(this).is(":radio")) {
        var inputName = $(this).attr("name");
        var labelFor = $(this).attr("id");
        $(this).click(function() {
            $("input[name=" + inputName + "]").each(function() {
                var labelFor = $(this).attr("id");
                $("label[for=" + labelFor + "]").removeClass("error");
            });
        });
    };
});

我已经把你的"想法"转换成代码了。看看这是否适合你…

// Figure out the name associated with each label that has an error
$(".error").each(function() {
    var m = $(this).attr('for');
    // Find the checkbox or radio button that has that ID
    $("input[id=" + m + "]").each(function() {
        // Figure out the checkbox or radio buttons name
        var n = $(this).attr('name');
        // Find the rest of the checkboxes or radio buttons with the same name
        $("input[name=" + n + "]").not(this).each(function() {
            // Find those inputs IDs
            i = $(this).attr('id');
            // Find labels with those names
            $("label[for=" + i + "]").each() {
                // Clear the errors off of those labels
                $(this).removeClass("error");
            });
        });
    });
});