$(function(...">

JQuery validation ONLY when selecting specific radio buttons

I have this simple check bit in my form:

<script type="text/javascript"> $(function() { $("#postform").validate({ rules: { post_title: "required", post_url: "required", post_code: "required", post_content: "required", post_tags: "required" } }); }); </script> 

BUT I don't want to require post_url or post_code if certain radio buttons are not checked as they are hidden when I select them. For example, here are the radio stations:

 <li><label for="r1"><input type="radio" name="post_category" id="r1" value="12" checked="checked" /> Share an Article</label></li> <li><label for="r4"><input type="radio" name="post_category" id="r4" value="14" /> Share a Link</label></li> <li><label for="r3"><input type="radio" name="post_category" id="r3" value="13" /> Share some Code</label></li 

and then this is jquery code that hides or shows them:

 <script type="text/javascript"> jQuery(document).ready(function($) { $("input[name='post_category']").change(function() { $("#discussion-label").toggle(this.value == "12"); }); $("input[name='post_category']").change(function() { $("#code-container").toggle(this.value == "13"); $("#code-label").toggle(this.value == "13"); }); $("input[name='post_category']").change(function() { $("#link-container").toggle(this.value == "14"); $("#link-label").toggle(this.value == "14"); }); $("input#r1:checked").change(); $("input#r3:checked").change(); $("input#r4:checked").change(); }); </script> 

So the idea is that when the user selects the first switch, only post_title, post_content and post_tags will be checked. If the user selects the second switch, he will ALSO check the post_url field, if they select the third switch, then he will check the post_code field, but NOT post_url is larger and vice versa.

Can anyone help? Thanks

+4
source share
1 answer

You can have conditional validation using an object with the value "depends" instead of the string "required" for your validation object, for example:

 $("#postform").validate({ rules: { post_title: "required", post_url: { required: { depends: function() { return $('input[name=post_category]:checked').val() == '14'; } } }, post_code: { required: { depends: function() { return $('input[name=post_category]:checked').val() == '13'; } } }, post_content: "required", post_tags: "required" } }); 

The function is automatically used by the validation framework to verify whether validation should be performed. If the function returns true, it will check, otherwise it will not. In this case, each function determines which of the radio stations is checked, and then compares this radio value with the required value, which is necessary for verification.

+12
source

Source: https://habr.com/ru/post/1344171/


All Articles