How to make an email field conditionally required in Formassembly

Viewed 363

We are using Formassembly to create our forms and currently we have a form which is both used by internal and external users. There is a checkbox in the form which distinguishes between internal & external users. I need the code to check if the "Internal" checkbox is ticked or not, if the "Internal" checkbox is ticked the email field needs to be optional otherwise the email field needs to required. I assume it can be achieved by Javascript or please advise if there is any other way. I have no idea in coding but tried looking up online and tried to code but it doesn't work. Please help.

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

<script>


{

//#tfa_78 is the checkbox

 

 
  if($("#tfa_78").is(":checked"))  { 

//#tfa_1 is the email field
 
    this.getField("#tfa_1").required = false;

    }

  else 
  {

    this.getField("#tfa_1").required = true;

  }

  });

});

</script>

3 Answers

You can use the property onblur on your checkbox to trigger a JS function that check its status an then require or not your email input. The onblur will be trigger each time the checkbox looses focus (so each time it will be changed or clicked).


<input id="tfa_78" type="checkbox" onblur="mailRequired(this.checked)"></input>
<input id="tfa_1" type="mail"></input>


<script>
function mailRequired(checked) {
    if (checked) {
        document.getElementByID('tfa_1').required = true;
    } else {
        document.getElementByID('tfa_1').required = false;
    }
}
</script>

Due to having JQuery, we can solve the problem as follows

$(document).ready(function() {

//#tfa_78 is the checkbox

  $("#tfa_78").change(function(){

 
  if($("#tfa_78").is(":checked"))  { 
//#tfa_1 is the email field
    $("#tfa_1").attr("placeholder","Optional Email");
    $("#tfa_1").attr("required",false)

    }

  else 
  {
    $("#tfa_1").attr("placeholder","Requierd Email");
    $("#tfa_1").attr("required",true)

  }

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="tfa_78" /> Local User
<br />
<input type="email" id="tfa_1" required placeholder="Requierd" />

I managed to get it work. Here is my code. But what if I need it to work if the checkbox is not ticked? will it be $("#tfa_78").is(":checked == false") ?


<script>


$(document).ready(function() {

//#tfa_78 is the checkbox

  $("#tfa_78").change(function(){
  $("#tfa_78").is(":checked")  
  $('#tfa_1').addClass('required')
  });

});

</script>
Related