Driftwood Driftwood - 1 year ago 62
jQuery Question

Jquery Form Validation - using if statement for validation?

I have a form that I am using jquery/mail chimp.

A portion of the form is hidden and shows (using Jquery Slide()) if a radio button is checked.

Every thing works great as it should.

The Problem:

The form sets to validate the sections that are hidden as well. However some users will not always check the radio button meaning that the form will faulter because the hidden forms will not validate since they are not filled in.

Does any body have any work arounds on this?

Here is the code.

The trigger (shows the rest of the form.)

<div id="accordionup">
<input name="group[5]" type="radio" id="mce-group-5-1" value="32"checked="checked" />
<label for="mce-group-5-1">No

When the user selects the radio button the form below slides down. All I would need it to do is add
to a couple (this is key too) not all the fields that slide down. So essentially some kind of conditional/if statement.

<div id="accordion">
<div class="mc-address-group">
<li class="statefield">
<label for="mce-MMERGE1-state">State:</label>
<input type="text" value="" maxlength="20" name="MMERGE1[state]" id="mce-MMERGE1-state" class="" />
<li class="zipfield">
<label for="mce-MMERGE1-zip">Zip Code:</label>
<input type="text" value="" maxlength="10" name="MMERGE1[zip]" id="mce-MMERGE1-zip" class="" />
<li class="countryfield">

I am using this for the slide down

$('#accordion').click(function() {
$('#slider').slideDown('slow', function() {


$('#accordionup').click(function() {
$('#slider').slideUp('slow', function() {



Thank you.

Answer Source

Try this:

$("#mce-group-5-1").change(function() {

You can add more IDs in the selector, separated by commas. .toggleClass() will check if the selected element has the specified class. If it has it, it will remove it, if it doesn't, it will add it.

It seems that you are using the jQuery Validate plug-in, so as an alternative, you could add and remove rules on the fly with .rules() like this:

$("#mce-group-5-1").change(function() {
    if ($(this).is(":checked")) {
        $("#mce-MMERGE1-state").rules("add", "required");
    } else {
        $("#mce-MMERGE1-state").rules("remove"); // remove all validation rules

See a complete demo on JSFiddle (uses a checkbox instead of radio buttons).

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download