javascript – How to make an email field conditionally required in Formassembly

javascript – How to make an email field conditionally required in Formassembly

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>

javascript – How to make an email field conditionally required in Formassembly

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>

Leave a Reply

Your email address will not be published.