javascript - jQuery 组复选框问题

标签 javascript jquery checkbox

我有两组复选框newBuildingoldBuilding

  1. 这里的想法是我只能选择该组中的一个复选框。
  2. 在每个组中都有复选框名称其他区域,因此当我单击它时,它将显示和隐藏旁边的文本框。

现在为了实现第一点,举例来说,我们已经选中了 oldBuilding 复选框,如果我单击其中一个 newBuilding 复选框,那么它将删除该复选框来自 oldBuilding 组,但 ​​newBuilding 复选框不会被选中,而只会获得焦点,我必须再次单击才能检查。

我发现当我调用触发事件时会发生上述问题。我怎样才能克服这个问题

其他区域代码

$("#chkOldBuildingOtherAreas").change(function () {
  if ($("#chkOldBuildingOtherAreas").is(":checked"))
     $("#txOldOtherAreas").show();
  else
    $("#txOldOtherAreas").hide();
  });

$("#chkNewBuildingOtherAreas").change(function () {
  if ($("#chkNewBuildingOtherAreas").is(":checked"))
    $("#txNewOtherAreas").show();
  else
    $("#txNewOtherAreas").hide();
});

从其他组中删除复选标记的代码

$("input[name='oldBuilding']").change(function () {
  if ($("input[name='newBuilding']:checked").length > 0) {
    $("input[name='newBuilding']").removeAttr('checked');
    $("#chkNewBuildingOtherAreas").trigger("change");
  }
});

$("input[name='newBuilding']").change(function () {
  if ($("input[name='oldBuilding']:checked").length > 0) {
    $("input[name='oldBuilding']").removeAttr('checked');
    $("#chkOldBuildingOtherAreas").trigger("change");
  }
});

我的jsfiddle

https://jsfiddle.net/milindsaraswala/wchrwjnx/

最佳答案

https://jsfiddle.net/1ny36nwL/4/

var groups = ['.oldGroup', '.newGroup'];
$(groups.join(',')).find('input[type=text]').hide();

function resetGroup(selector) {
    //clear and hide texts
    $('input[type=text]', selector).val('').hide();
    //uncheck boxes
    $('input[type=checkbox]', selector).removeAttr('checked');
}

$("input[name='oldBuilding']").change(function(e) {
    if (this.id == 'chkOldBuildingOtherAreas') {
        $("#txOldOtherAreas").toggle();
    }
    resetGroup('.newGroup');
});

$("input[name='newBuilding']").change(function(e) {
    if (this.id == 'chkNewBuildingOtherAreas') {
        $("#txNewOtherAreas").toggle();
    }
    resetGroup('.oldGroup');
});

如您所见,我添加了 groups var,它可以包含多个组(不仅仅是两个),但需要对代码进行更多更改才能使其工作

您需要通过诸如 $(this).closest('.form-group').id 之类的方式检测当前组的 id/class 并重置除当前组之外的每个组。这样你就可以只留下一个通用的更改函数

哦,您还需要为包含文本输入的复选框添加一些类,如果单击该复选框,则会触发输入切换。所以它不会是 if (this.id == 'chkNewBuildingOtherAreas') { 而是类似 if ($(this).hasClass('has-input'))

关于javascript - jQuery 组复选框问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527604/

相关文章:

javascript - window.onload 与 $(document).ready()

Javascript CSV 导出逗号问题

javascript - JavaScript 中的 match 与 exec

javascript - 如何使用 jQuery 单独引用动态生成的 Bootstrap 面板

jquery - 进度条宽度

javascript - 改变动画速度

javascript - jQuery 复选框自动禁用和重新启用

javascript - 文本区域的占位符? (ExtJS)

javascript - 复选框未选中状态

php - 使用 jQuery 选择表中的所有复选框