I have a form with a select with 3 options "Blank", "Yes" and "No". I also have a text input which is part of this situation. My HTML is as follows (Extract):<div class="row"> <div class="col-sm-4 col-md-4"> <select class="form-control" id="medical" name="medical" onchange=" if(this.value == 'medyes') { document.getElementById('medcon-text').style.display = 'block'; } else { document.getElementById('medcon-text').style.display = 'none';} "> <option value="Select an option"></option> <option value="medyes">Yes</option> <option value="medno">No</option> </select> </div><!--close medical select--> </div><div class="row"> <div class="col-sm-12 col-md-12"> <div id="medcon-text" style="display:none;"> <label class="control-label">If so please specify:</label> <input type="text" class="form-control" id="medicaltext" name="medicaltext" placeholder="Enter your disability or medical condition"> </div> </div> <!--close medical condition--> </div> <!--close row-->jQuery Validate Code (Extract):$("#online-application").validate({ rules: { medical: { required: true }, medcon: { required: $("#medical").val() == "medyes" }, }, messages: { medical: "Please select an option.", medicaltext: "Please enter your medical condition.", },My question is, how do I make the select a required field and IF the select value is "Yes"/"medyes" then make the medicaltext input a required field. However, if the select value is no or blank then the medicaltext input must NOT be required. 解决方案 You need to use a function() that returns true/false in conjunction with the depends property.rules: { medical: { required: true }, medicaltext: { // <- NAME attribute of the input required: { depends: function() { return ($("#medical").val() == "medyes"); } } },},Within the .validate() method, rules can only be assigned using the name attribute of each input element. Since I don't see any input with name="medcon", then this needs to be changed to match the name on the text input element.See documentation for depends: jqueryvalidation.org/validate/#rulesFor required to work on a select, you also need to change this line...<option value="Select an option"></option>into this...<option value="">Select an option</option>DEMO: http://jsfiddle.net/34oo7nrg/ 这篇关于jQuery Validate-从选择中获取值,并基于该值使文本输入必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 17:35