Hide and Show Field Based on Field Value in Dynamics 365

Hide and Show Field Based on Field Value in Dynamics 365

Dynamics 365 allows developers to create dynamic and user-friendly forms using JavaScript. One of the most common customization requirements is showing or hiding fields based on the value selected in another field.

This functionality helps simplify forms, improves user experience, and ensures users only see fields that are relevant to their current business process.

Business Scenario

Suppose a Customer Type field contains the following values:

When Business is selected, additional fields such as Company Name and GST Number should become visible. Otherwise, those fields should remain hidden.

Benefits of Dynamic Field Visibility

Create JavaScript Function

function hideShowFields(executionContext)
{
   var formContext =
   executionContext.getFormContext();
}

Get Field Value

var customerType =
formContext.getAttribute(
"new_customertype")
.getValue();

Show or Hide Fields

if(customerType == 100000001)
{
   formContext.getControl(
   "new_companyname")
   .setVisible(true);

   formContext.getControl(
   "new_gstnumber")
   .setVisible(true);
}
else
{
   formContext.getControl(
   "new_companyname")
   .setVisible(false);

   formContext.getControl(
   "new_gstnumber")
   .setVisible(false);
}

Register the Function

  1. Create a JavaScript Web Resource.
  2. Upload the script.
  3. Add the library to the form.
  4. Register the function on Form OnLoad.
  5. Register the function on Field OnChange.
  6. Save and Publish customizations.
Important: Always register the function on both OnLoad and OnChange events to ensure field visibility remains correct when records are opened or modified.

Common Use Cases

Best Practices

Key Takeaways