javascript - 使用 jQuery 进行检查/取消检查不起作用

标签 javascript jquery asp.net-mvc razor

我试图使复选框的行为类似于我的 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);
    }
  });
});

关于javascript - 使用 jQuery 进行检查/取消检查不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391810/

相关文章:

javascript旋转div消失

asp.net-mvc - 根据语言在文件夹中组织 ASP.NET 资源文件

c# - EF——无法确定类型之间关联的主体端

JavaScript:将对象绑定(bind)到 DOM 元素

c# - 使用C#访问网站

javascript - IE9内存泄漏

c# - vb.net asp.net webforms 应用程序 > c# asp.net mvc razor 应用程序

javascript - 通过 id name 检查元素是否有子节点

javascript - Jquery 插件对象 #<HTMLDocument> 没有方法 'observe' 问题

javascript - 使用扩展克隆时如何更新原始版本