Divine
Divine

Reputation: 11

How can I a field as required based on selection of radio button in a form

There is a custom radio button. On select of 'yes' of that button another field is there which should not be required

$("#btnFormSubmit").click(function() {
  var radioValue = $("input[name='CustomDuration']:checked").val();
  if (radioValue == 'Yes') {
    $("#frmCertificateRequirement").validate({
      rules: {
        ValidDurationMonths: {
          required: false
        }
      }
    })
  }

Upvotes: 1

Views: 66

Answers (2)

sanjay sisodiya
sanjay sisodiya

Reputation: 465

If you do not want to show the Required Message when the radio button is checked . Then There is no closing of your code , please correct it.

HTML Code

<form name="btnFormSubmit" id="btnFormSubmit" method="post">
    <div>
        <label for="username">Username/Email</label>
        <input type="text" name="username" autocomplete="false" readonly onfocus="this.removeAttribute('readonly');">
    </div>
    <button type="submit" id="btnFormSubmit">submit</button>
</form>
<input type="checkbox" name="CustomDuration" id="CustomDuration" value="Yes">checkbox

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>

JQUERY Code with perfect closing

$("#btnFormSubmit").click(function () {
   var radioValue = $('input[name="CustomDuration"]:checked').val();

   if (radioValue == "Yes") {
      $("#login_form").validate({
         rules:{
            username: 
            {
                required: false,
            }
         },
      });
    }
 }); /*You have missing this closing*/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly you need to call validate() when the page loads, not when the submit button of the form is clicked.

With regards to your issue, the required property will accept a selector you can use to dynamically set the validation requirements for the element. Try this:

$("#frmCertificateRequirement").validate({
  rules: {
    ValidDurationMonths: {
      required: 'input[name="CustomDuration"]:checked'
    }
  }
});

Upvotes: 1

Related Questions