Marc Berman
Marc Berman

Reputation: 53

jQuery Validate - Get value from select and based on the value make text input required field

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.

Upvotes: 2

Views: 6075

Answers (1)

Sparky
Sparky

Reputation: 98738

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/#rules


For 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/

Upvotes: 4

Related Questions