Creating dynamic form behaviors using JavaScript

Loading

Power Pages (formerly Power Apps Portals) support form customization through JavaScript to deliver dynamic, interactive, and user-friendly experiences. By writing JavaScript, you can manipulate form behavior based on user input, time, roles, or data.


Common Use Cases for Dynamic Behavior

BehaviorExample
Show/Hide FieldsShow “Other” text field only if “Other” is selected in dropdown
Enable/Disable FieldsDisable fields unless user has a specific role
Set Default ValuesSet a field value based on the current date or another field
Validate InputEnsure email ends with specific domain
AutofillAutofill address based on postal code
Conditional FormattingHighlight mandatory fields not filled

Getting Started

  1. Go to Portal Management App.
  2. Navigate to Web Pages > Entity Forms.
  3. Under Additional Settings, scroll to Custom JavaScript.
  4. Add your script here or reference a Web File containing JS code.

Basic JavaScript Template

$(document).ready(function () {
// Wait for the form to fully load
setTimeout(function () {
// Example: Show/hide a field based on dropdown selection
$('#your_dropdown_field').change(function () {
if ($(this).val() === 'Other') {
$('#other_reason_field').closest('tr').show();
} else {
$('#other_reason_field').closest('tr').hide();
}
});

// Initially hide the field
$('#other_reason_field').closest('tr').hide();
}, 500); // Add delay to ensure all fields are rendered
});

Examples

A. Enable Field Only if Checkbox is Checked

$('#consent_checkbox').change(function () {
if ($(this).is(':checked')) {
$('#email_field').prop('disabled', false);
} else {
$('#email_field').prop('disabled', true);
}
});

B. Set a Default Date (Today)

const today = new Date().toISOString().split('T')[0];
$('#birthdate').val(today);

C. Custom Validation

$('form').submit(function (e) {
const email = $('#email_field').val();
if (!email.endsWith('@yourdomain.com')) {
alert("Email must end with @yourdomain.com");
e.preventDefault();
}
});

D. Hide a Field Based on Web Role (using Liquid)

In your Web Template:

{% if user.roles contains 'Manager' %}
<script>
$(document).ready(function () {
$('#manager_notes').show();
});
</script>
{% endif %}

Best Practices

TipDescription
Use setTimeout()Forms may load with a delay—ensure DOM is fully rendered
Use field IDs carefullyUse browser Dev Tools (F12) to inspect actual field IDs
Store JS in Web FilesFor reuse and modularity
Test on mobileEnsure behaviors work on all screen sizes
Use Liquid to inject dataFor role-based dynamic scripting

Debugging Tools

  • Use browser Developer Tools (F12) to inspect form fields
  • Use console.log() to test and debug
  • Disable JS temporarily to test fallback behavior

Leave a Reply

Your email address will not be published. Required fields are marked *