GSto
GSto

Reputation: 42350

jquery validation, make fields conditionally required?

Using the jQuery plugin found here:

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

I have a form, that when certain checkboxes are selected, additional fields are shown to the user. I would like to make these fields required when they click the checkbox, and unrequired if they unselect it.

Is there a way to dynamically set requirements for elements?

Upvotes: 1

Views: 3922

Answers (2)

dah97765
dah97765

Reputation: 687

Just to expand on the answer above by K2so:

If you put something like this in the document ready:

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

where the element with id reasonCode is equivalent to your checkboxes. On change, it calls the function 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');

    };
}

And that should be plenty to get you going. The hideMe and showMe classes are self explanatory :)

Upvotes: 1

K2so
K2so

Reputation: 982

I think simplest approach is to attach the "required" class using jquery to these elements on click.

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

Upvotes: 4

Related Questions