Jake
Jake

Reputation: 1057

jQuery form validation; field required if checkbox selected

I'm currently working with this; http://www.geektantra.com/2009/09/jquery-live-form-validation/

I'm trying to add validation so if a user checks the Location box, the "L2" field would have to be required. How can I achieve this with this plugin? Would I have to mix in the checkbox expression?;

expression: "if (isChecked(SelfID)) return true; else return false;",

Here's the plugin functions

<script type="text/javascript">
            jQuery(function(){
                jQuery("#v1").validate({
                    expression: "if (VAL) return true; else return false;",
                    message: "Please enter your name"
                });
            });
</script>

Here's the form

<form method="post" id="contactform" action="/form.php" >
<h5>Category:</h5>
<p><input type="checkbox" name="Location" value="Checked" onclick="toggle_visibility('f1');"> <span class="a1">- Location</span><br><div id="f1" style="display:none">Where are you located?<br /><input name="L2" id="L2" type="text"  /></div></p>

<h5>Name:</h5>
<p><input name="Name" id="v1" type="text" /></p>
<p><div><input name="submit" type="submit" value="Submit"/></div></p>
</form>

Upvotes: 0

Views: 4888

Answers (3)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Do you mean:

rules: {
      fieldName: {
        required: {       
          depends: function() {
            return $("input[name='checkbox']:checked")
          }
        }
      }
    }

Upvotes: 3

gregdev
gregdev

Reputation: 1943

For some reason Sudhir's answer didn't work for me - I had to modify it:

rules: {
  fieldName: {
    required: {       
      depends: function(element) {
        return $("input[name='checkbox']:checked").length == 1
      }
    }
  }
}

Upvotes: 1

Jules
Jules

Reputation: 1423

Sudhir's answer is correct. All you have to do is use it as options when initialising the validation.

var opt = {};//copy from Sudhir's post of course change the field name as required.
$("form").validate(opt);

Upvotes: 0

Related Questions