【问题标题】:jquery value in dropdown selected disable checkbox下拉列表中的 jquery 值选中禁用复选框
【发布时间】:2011-07-16 11:45:14
【问题描述】:

当下拉菜单的选定值不是 0 时,我尝试使用 jquery 禁用复选框。我的问题是当我选择值为 0 的项目时,复选框被禁用并获取复选框禁用我必须选择至少两个或更多值才能禁用复选框。

我的代码示例如下:

example code at js fiddle

When the selected value is 0 I want the checkbox and drop down to be enabled and when the selected value is anything other than 0 I want to disable the checkbox.无论我是从第一行、底部、行还是中间行开始,我也希望它能够工作。

【问题讨论】:

    标签: jquery select checkbox drop-down-menu


    【解决方案1】:

    如果我对您的问题的理解是正确的,应该这样做:

    $("select").change(function() {
        $(this).closest("td").prev().find(":checkbox").prop("disabled", $(this).val() !== "0");
    });
    
    $(":checkbox").change(function() {
       $(this).parent().next().find("select").prop("disabled", this.checked);
    });
    

    Your updated fiddle.

    【讨论】:

    • 感谢它几乎可以工作。我还希望能够在选中复选框时禁用下拉菜单
    • @larry - 我已经更新了答案和演示。请看一看。
    • 效果很好。我尝试添加一个仅在所选值为一个时才会出现的文本框,但我只能让它在第一个下拉菜单中工作。我做错了什么?
    • 您需要在选择更改处理程序中插入相对于当前选择元素的文本框,例如$(this).after("<input type='text'/>");。你应该阅读更多关于 DOM 树遍历的内容:api.jquery.com/category/traversing
    【解决方案2】:

    试试这个(works for me):

    $("select").change(function() {
      var $this = $(this),
          $checkbox = $this.parent().prev().find("input");
    
      if ($this.val() != 0) {
        $checkbox.attr("disabled", true);
      } else {
        $checkbox.removeAttr("disabled");
      }
    });
    
    $(":checkbox").change(function() {
      var $this = $(this),
          $select = $this.parent().next().find("select");
    
      if ($this.is(":checked")) {
        $select.attr("disabled", true);
      } else {
        $select.removeAttr("disabled");
      }
    });
    

    【讨论】:

    • 感谢它也有效。如果我想添加一个文本框来显示/隐藏我会做类似的事情: if ($this.val() != 0) { $checkbox.attr("disabled", true); $(":text").hide(); } else if ($this.val() !== 1) { $checkbox.attr("disabled", true); $(":text").show(); } else { $checkbox.removeAttr("disabled"); }});
    【解决方案3】:

    这是因为在“更改”事件中,您获得的值是更改实际完成之前的值,因此用户“现在”所做的更改要等到下次事件触发时才会显示。

    您想使用诸如 onblur、onmouseup 或 onkeyup 之类的东西在更改后通知您要更改复选框的属性。

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2015-01-31
      • 2018-08-21
      相关资源
      最近更新 更多