molleman
molleman

Reputation: 2946

Trouble with jQuery validate rules for Form

Hello I am trying to use jQuery Validation ,

Basically i have a form , where certain elements are required no matter what,

but then i have other fields that are only required is a checkbox is selected

i am using jQuery Validation here is a link to documentation

Here is my form

<form action="http://www.funnytennisstories.com/save-story.php" method="POST" name="story-form" id="storyForm">
<fieldset>
    <label for="Your Story">Your Story</label>
    <textarea class="required" name="your-story" cols="" rows=""></textarea>
    <label for="free-wrist-band">Check the box to receive a free tennis wristband &nbsp;  </label>
    <input id="free-wrist-band-check-box" name="free-wrist-band" type="checkbox" />
    <label for="address">Address</label><input id="address" class="txtClass shipping" name="address" type="text" >
    <input type="submit" name="story-post" value="Post Your Story"/>
 </fieldset>
</form>

So i have cut it down quite a bit, but basically if free-wrist-band-check-box is selected i should have to put in address text, but if it is not checked i should not have to put in any text

Here is the javascript i have written, but if the checkbox is selected it does not work

<script>

 $(document).ready(function(){

    $("#storyForm").validate({
    debug:true,
       rules: {
         shipping: {
             required: $("#free-wrist-band-check-box:checked")
           }
       }
    });
});

Debug is also not showing in firebug lite(and the inspect element tool) on chrome and inspector on safari

Any Ideas guys

Upvotes: 0

Views: 235

Answers (1)

The Alpha
The Alpha

Reputation: 146191

Add this inside $(document).ready(function(){...})

$('#free-wrist-band-check-box').on('change', function(){
    if($(this).is(':checked')) $("#address").rules("add", "required");
    else $("#address").rules("remove", "required");
});

So the address text box will be required only if the checkbox is checked.

DEMO.

Upvotes: 1

Related Questions