Javascript 选中复选框后,从标签中删除类
我已经编写了一个基本表单验证脚本,现在我正在尝试重置如果用户没有填写必填字段时发生的错误 对于复选框和单选按钮,我将类Javascript 选中复选框后,从标签中删除类,javascript,jquery,Javascript,Jquery,我已经编写了一个基本表单验证脚本,现在我正在尝试重置如果用户没有填写必填字段时发生的错误 对于复选框和单选按钮,我将类error添加到它们的标签中。此文件的HTML代码如下所示: <input class="required" id="Example31" name="Example3" type="checkbox" /> <label for="Example31" class="error">Example Input 3 Option 1</label>
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>
如何在不修改HTML的情况下删除错误?我在画一张空白的画。以下是我的想法:
// 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");
});
});
});
});
我可以自己用这个来解决这个问题:
$("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");
});
});
};
});
您是否试图一次从所有标签中删除错误?何时需要删除错误?当
复选框
未选中时,当它变为选中时。对不起,我一贴出来就出去吃午饭了。几分钟后,我将在下面的错误中测试代码。它在最后一次}
时告诉我一个错误,说未捕获的语法错误:意外标记}
$("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");
});
});
};
});