Search code examples
javascripthtmlrequired

required fields should only be needed upon element display


I have a form where a user is asked if he has an authorized representative in form of a radio button. If the user choose the 'yes' option, it will show more fields about the representative and it has a required input 'representative email'.

Is there a way for it to be only needed when the user choose the yes option? The form is not submitting because it keeps finding the value of this required field if the user chooses the 'no option'.

<form>

<div class="onBehalfOf">
<input type="radio" checked="checked" name="Radio" id="yes" value="Yes">
<label for="yes"> Yes</label>
<input type="radio" name="Radio" id="no" value="No">
<label for="no"> No</label>
</div>

<div class="authorizedRep">
Email:
<input type="email" required />
</div>

<input type="submit" label="submit" />

</form>

js Fiddle Example


Solution

  • With a small change you can toggle the required attribute on the email input when you show/hide the fields. You just need to add the appropriate emailInput class to the element.

    $('.onBehalfOf input:radio').change(function() {
      if ($(this).is(':checked') && $(this).val() == 'No') {
        if ($('.authorizedRep').hasClass("hide")) {
    
        } else {
          $('.authorizedRep').addClass("hide");
          $('.emailInput').removeAttr('required');
        }
      }
    
      if ($(this).is(':checked') && $(this).val() == 'Yes') {
        $('.authorizedRep').removeClass("hide");
        $('.emailInput').attr('required');
      }
    });