当复选框被选中时,从标签中删除class
When a checkbox becomes checked, remove class from labels
我已经编写了一个基本的表单验证脚本,现在我正试图重置如果用户不填写所需字段时发生的错误。
对于复选框和单选按钮,我已经将类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的情况下删除错误?我脑子一片空白。我是这么想的:
- 找出与每个有错误的标签相关联的名称
- 查找具有该ID的复选框或单选按钮
- 找出复选框或单选按钮名称
- 查找其余同名的复选框或单选按钮
- 查找这些输入id
- 查找具有这些名称的标签
- 清除这些标签的错误
虽然我很失落。如果有人能帮忙的话,我将不胜感激。
我自己解决了这个问题:
$("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");
});
});
});
});
相关文章:
- iframe正在添加标签,需要删除它们
- 兰吉 |如何在 span 标签上使用单击事件删除突出显示的文本
- jQuery从标签中删除括号/文本
- 删除$fromtataLayertotal-google标签管理器
- 通过点击文本区域添加和删除多个标签
- 使用 JavaScript 删除标签之间的每个空格
- 删除对HTML5视频标签的控件(播放,暂停等)
- 删除高图表数据标签上的阴影/背景发光
- 当歌曲在html音频标签中回放时,我如何删除间隙
- (X-Editable)与(Select2标签)不工作,可以't填充当前标签并跟踪添加/删除的标签
- 删除 p标签之间
- 当请求时,我如何从文本区域删除null.GetAttribute为null,以及如何从servlet修改标签的可见性
- 添加和删除geojson层的传单标签
- 删除<脚本>标签中的<头部>在所有Drupal 7页中
- 如何修改此javascript使其'll删除两者<b>并且<i>标签
- 在文档中搜索文本以删除的文本超过找到它的标签
- 我正在尝试制作一个锚标签删除功能
- 垂直标签:删除没有jQuery或固定位置属性的UL和DIV中断
- 按标签删除谷歌地图标记
- Jquery标签删除导致换行