Jquery Validate dropdown required if field empty -
i'm trying make dropdown required if #category field empty.
thanks!
jquery attempt #1:
$("#uploaddocsform").validate({ rules: { name: { required: true, minlength: 2, maxlength: 255 }, cat_id: { required: function(element) { return $("#category").val() == ''; } } }, messages: { name: 'please enter <b>document name</b>.', cat_id: 'please select <b>category</b>.' } });
jquery attempt #2:
$("#uploaddocsform").validate({ rules: { name: { required: true, minlength: 2, maxlength: 255 }, cat_id: { required: { depends: function(element) { return $("#category").val() == ''; } } } }, messages: { name: 'please enter <b>document name</b>.', cat_id: 'please select <b>category</b>.' } });
html:
<form name="uploaddocsform" id="uploaddocsform"> <label for="name">document name</label> <input name="name" id="name" type="text" class="textbox"/> <label for="cat_id">category</label> <select name="cat_id" id="cat_id" class="dropdown"> <option selected>please select category</option> <option>------------------------</option> <option value="1">test cat</option> </select> <label for="category">new category</label> <input name="category" id="category" type="text" class="textbox"/> </form>
$("#uploaddocsform").validate({ rules: { name: { required: true, minlength: 2, maxlength: 255 }, cat_id: { required: { depends: function(element) { return $("#category").val() == ''; } } } }, messages: { name: 'please enter <b>document name</b>.', cat_id: 'please select <b>category</b>.' } });
the depends function checks if category element filled, , if second required. otherwise optional (meaning can filled).
use cases:
- category filled, cat_id empty : invalid
- category filled, cat_id filled : valid
- category empty, cat_id empty : valid
- category empty, cat_id filled : valid
Comments
Post a Comment