Check/Uncheck 使用 jQuery 无效

Check/Uncheck using jQuery not working

我试图让复选框在我的 ASP .NET MVC Web 应用程序中表现得像单选按钮。我将大约 20-30 个复选框分成两部分。例如:

<input type="checkbox" id="@riggingType.RiggingTypeId 1" name="RiggingTypePlus" 
       value="@riggingType.RiggingTypeId" 
       checked="@riggingTypeIds.Contains(riggingType.RiggingTypeId)" />

<input type="checkbox" id="@riggingType.RiggingTypeId 2" name="RiggingTypeMinus" 
       value="@riggingType.RiggingTypeId" 
       checked="@riggingTypeIds.Contains(riggingType.RiggingTypeId)" />

目标:

我想让复选框的行为方式是,如果 Plus 复选框被选中,那么 Minus 会自动取消选中,反之亦然。我已经编写了以下代码来尝试实现此功能:

$(":checkbox").change(function () {
  var inputs = $(this).parents("form").eq(0).find(":checkbox");
  var idx = inputs.index(this);
  if (this.name.substring(this.name.length - 4, this.name.length) === "Plus") {
      // just trying to check if I am getting the right it 
      // and I am getting the right id
      // alert(inputs[idx + 1].id);

      // But this does not work
      $("#" + inputs[idx + 1].id).prop('checked', false);
  }
});

我是不是做错了什么:

$("#" + inputs[idx + 1].id).prop('checked', false);

任何帮助将不胜感激。

我知道我可以使用单选按钮并按相同的名称对它们进行分组,但我在循环中呈现元素,因此它们都具有相同的名称但值不同,我不想以不同的方式命名它们,因为我在服务器端使用这些数据...有更好的方法吗?

答案:

使用以下方法完成此工作:

$(document).ready(function(){
    $(":checkbox").on('click', function () {

    var $this = $(this);
    var inputs = $this.closest("form").find(":checkbox");
   if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus" && $this.attr('checked')) {
        $this.next().prop('checked', false);
    }
        else
        {
            $this.prev().prop('checked', false);
        }
  });
});

Fiddle Link

fiddle: https://jsfiddle.net/24gmnjwm/1/

$(document).ready(function(){
  $(":checkbox").on('click', function () {
    var $this = $(this);
    var inputs = $this.closest("form").find(":checkbox");
    if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus") {
        $this.next().prop('checked', false);
    }
  });
});

如果我们可以假设 "plus" 复选框总是出现在其相关的 "minus" 复选框之前,那么这将起到作用:

$(":checkbox").change(function () {
    if ($(this).prop("name").match(/Plus$/)) {
        $(this).next().prop("checked", !$(this).prop("checked"));
    } else {
        $(this).prev().prop("checked", !$(this).prop("checked"));
    }
});

示例表格:

<form>
<input type="checkbox" name="RiggingTypePlus" value="2" checked />
<input type="checkbox" name="RiggingTypeMinus" value="2" />
<input type="checkbox" name="RiggingTypePlus" value="3" />
<input type="checkbox" name="RiggingTypeMinus" value="3" />
<input type="checkbox" name="RiggingTypePlus" value="4" />
<input type="checkbox" name="RiggingTypeMinus" value="4" />
<input type="checkbox" name="RiggingTypePlus" value="5" />
<input type="checkbox" name="RiggingTypeMinus" value="5" />
</form>

fiddle