0

Here is my current code which works when the checkbox is changed. But I need it to make the required fields required again if the checkbox is unchecked (changed again). Ideally I guess I would want to be able to check the value of the checkbox and then either require or unrequire the lightning input fields based on it's new value.

HTML:

<lightning-input-field field-name="Attorney_Driven_Merger_and_Acquistion__c" onchange={requiredFieldsChanged}></lightning-input-field>

JS:

requiredFieldsChanged(event){
        this.template.querySelectorAll('lightning-input-field').forEach(element => {           
            if(element.fieldName=='Auto_Agency__c', 'Auto_Carrier__c'){
            element.required=false;
            }
New contributor
John Schroeder is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

You can do that:

requiredFieldsChanged(event) {
  [...this.template.querySelectorAll('lightning-input-field')]
  .filter((element) => ['Auto_Agency__c','Auto_Carrier__c'].includes(element.fieldName))
  .forEach((element) => element.required = event.target.checked);
}

Where event.target.checked should be the value of the checkbox. I haven't used lightning-input-field, so you might need to check and see what the actual property is.

6
  • So in my case the fields start as required in the form. If the checkbox is checked I want to make them not required. Basically the checkbox being checked is the exception that the user needs to indicate so that they don't need to fill out the normally required fields. So would this be reversed in some way? I SO appreciate your assistance with this! – John Schroeder May 4 at 14:04
  • @JohnSchroeder yes, you could reverse it, as in: element.required = !event.target.checked. – sfdcfox May 4 at 14:06
  • Still not working. Could the problem be that the fields are starting required? – John Schroeder May 4 at 14:40
  • Let me clarify the above. Checking the checkbox for the onchange event handler leaves those two fields still required. – John Schroeder May 4 at 14:42
  • Maybe event.target.value? Again, I'm not terribly familiar with lightning-input-field. – sfdcfox May 4 at 14:44

Your Answer

John Schroeder is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.