【问题标题】:Validate field with jquery only if checkbox is selectedValidate field with jquery only if checkbox is selected
【发布时间】:2011-01-28 17:02:44
【问题描述】:

我有几个同名的复选框,最后一个复选框基本上是“其他”,旁边有一个空文本字段。我正在使用 jquery 验证,我想在选中其他复选框时设置空文本字段。

不确定如何使用所有具有相同名称的复选框来执行此操作。

谢谢。

【问题讨论】:

    标签: jquery validation text checkbox field


    【解决方案1】:

    复选框具有相同的名称,但值不同。因此,您可以找到选定的值,然后检查特定值的值。我用单选按钮做了类似的事情。这是我的一条规则,如果 recurpattern 单选按钮的值为“day”,则需要 daypattern 字段。

            daypattern: {
                required: 
                    function(element){
                        return ($("input[name='recurpattern']:checked").val() == 'day')
                    }
    
            }
    

    在您的情况下,您的复选框集在 yourcheckboxes.val() 中有一个数组。因此,您检查您的测试值是否在该数组中。

    【讨论】:

      【解决方案2】:

      您可以选中所有这些复选框并使用 :last - 选择器 (http://api.jquery.com/last-selector/) 或者选择输入字段并使用 $(".myOtherInput").prev() 向上通过 DOM,如果它直接在您的字段前面。之后,您可以绑定函数以添加或删除class="required"

      【讨论】:

      • 我如何将 :last 和 :checked 放在一起?我找到了这个(docs.jquery.com/Plugins/Validation/Methods/…),这是我的代码,但它不起作用: $("#4_observerstxt").rules("add", { required: "#4_observers:last:checked" }); $("#4_observers:last").click(function() { $("#4_observerstxt").valid(); });
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多