jquery验证,有条件地要求字段吗?

时间:2011-11-02 16:47:24

标签: jquery validation

使用此处的jQuery插件:

http://docs.jquery.com/Plugins/Validation

我有一个表单,当选中某些复选框时,会向用户显示其他字段。我想点击复选框时需要这些字段,如果他们取消选中则不需要。

有没有办法动态设置元素的要求?

2 个答案:

答案 0 :(得分:4)

我认为最简单的方法是在点击时使用jquery将“required”类附加到这些元素。

http://api.jquery.com/addClass/

答案 1 :(得分:1)

只是为了扩展K2so上面的答案:

如果你准备好这样的东西:

$("#reasonCode").change(reasonCodeChange);

其中id为reasonCode的元素等同于您的复选框。在更改时,它调用函数reasonCodeChange ...

function reasonCodeChange(){

var strValue = $("#reasonCode option:selected").text()


strValue = strValue.substring(0,2);
    if(strValue== "7." || strValue== "9." || strValue== "10" ||strValue== "11" || strValue== "12"){
        $('#reasonCodeExpRow').addClass('showMe');
        $('#reasonCodeExp').addClass('required');
        $('#reasonCodeExpRow').removeClass('hideMe');
    }else{
        $('#reasonCodeExpRow').addClass('hideMe');
        $('#reasonCodeExp').removeClass('required');
        $('#reasonCodeExpRow').removeClass('showMe');

    };
}

这应该足以让你前进。 hideMe和showMe类是自解释的:)

相关问题