How to Enable and Disable Fields Using JavaScript in Dynamics 365

How to Enable and Disable Fields Using JavaScript in Dynamics 365

In Dynamics 365 and Model-Driven Apps, there are many business scenarios where fields should be enabled or disabled dynamically based on user input, record status, or business rules.

JavaScript provides a flexible way to control field accessibility and improve data quality by ensuring users can only modify fields when appropriate.

Why Enable or Disable Fields?

Disable a Field Using JavaScript

Use the setDisabled(true) method to make a field read-only.

function disableField(executionContext)
{
    var formContext =
        executionContext.getFormContext();

    formContext.getControl("new_comments")
               .setDisabled(true);
}

Enable a Field Using JavaScript

Use setDisabled(false) to make the field editable again.

function enableField(executionContext)
{
    var formContext =
        executionContext.getFormContext();

    formContext.getControl("new_comments")
               .setDisabled(false);
}

Enable or Disable Based on Another Field

function toggleField(executionContext)
{
    var formContext =
        executionContext.getFormContext();

    var status =
        formContext.getAttribute("new_status")
                   .getValue();

    if(status === 100000001)
    {
        formContext.getControl("new_comments")
                   .setDisabled(true);
    }
    else
    {
        formContext.getControl("new_comments")
                   .setDisabled(false);
    }
}
Important: Register the function on Form Load and On Change events to ensure field states update correctly.

Implementation Steps

  1. Create a JavaScript Web Resource.
  2. Add the script to the form.
  3. Register the function on Form Load.
  4. Register the function on field On Change event.
  5. Pass execution context.
  6. Save and publish customizations.

Common Use Cases

Best Practices

Key Takeaways