4

我已经编写了一个基本的表单验证脚本,现在我正在尝试重置用户未填写必填字段时出现的错误。

对于复选框和单选按钮,我已将类添加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. 清除这些标签上的错误

不过,我很茫然。如果有人可以提供帮助,将不胜感激。

4

2 回答 2

0

我已将您的“想法”转换为代码。看看这是否适合你...

// 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");
            });
        });
    });
});
于 2013-01-18T18:21:22.477 回答
0

我可以自己解决这个问题:

$("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");
            });
        });
    };
});
于 2013-01-18T19:34:44.100 回答