Preventing default behaviour in PowerApps portal web form

This article would be one of the easiest and shortest article but it needs writing about.

Sometimes, in PowerApps portal, we might have a requirement to prevent the default behaviour of the out-of-box buttons and check for some conditions before continuing. This might sound easy but the normal eventArgs.preventDefault() sometimes would not work and for someone with less experience this could be a problem that could take time to resolve.

To understand how and when to use :

event.preventDefault(), stopPropagation() or event.stopImmediatePropagation();

please read this article. As a developer you should also know when to combine them to achieve the desired result.

To cut the chase, in Powerapps portals webform and also Edit Basic form (formerly known as entity form) to prevent the click of a button’s default behaviour do the following:

document.querySelector(elementId).addEventListener("click", function(event) {
            if(<your condition>)
            {
            //Notify the user of the error
              event.preventDefault();
              event.stopImmediatePropagation();                      
            }                  
        }, true); 

I hope this would save someone some time.