將自訂 JavaScript 新增到表單

注意

自 2022 年 10 月 12 日起,Power Apps 入口網站為 Power Pages。 其他資訊:Microsoft Power Pages 現在已推出 (部落格)
我們很快就會遷移並將 Power Apps 入口網站文件與 Power Pages 文件併合。

基本表單多步驟表單步驟記錄都包含名為自訂 JavaScript 的欄位,可用來儲存 JavaScript 程式碼,讓您擴充或修改表單的視覺顯示或功能。

JavaScript 的自訂區塊會新增至頁面底部,剛好就在結束表單標籤元素之前的位置。

表單欄位

資料表欄位的 HTML 輸入識別碼會設定為屬性的邏輯名稱。 使用 jQuery 輕鬆選取欄位、設定值或執行其他用戶端操作。

$(document).ready(function() {
   $("#address1_stateorprovince").val("Saskatchewan");
});

重要

將選擇資料行新增到要在進多步驟單步驟或基本表單中使用的模型導向表單時,會做為下拉式伺服器控制項出現在入口網站頁面上。 使用自訂 JavaScript 將其他值新增至控制項時,將在頁面提交中出現「回傳或回撥引數無效」訊息。

其他用戶端欄位驗證

您有時可能需要自訂表單上的欄位驗證。 此範例強制使用者只有在偏好的連絡方式的其他欄位設定為 [電子郵件] 時,才能指定電子郵件。

注意

子格不支援用戶端欄位驗證。

if (window.jQuery) {
   (function ($) {
      $(document).ready(function () {
         if (typeof (Page_Validators) == 'undefined') return;
         // Create new validator
         var newValidator = document.createElement('span');
         newValidator.style.display = "none";
         newValidator.id = "emailaddress1Validator";
         newValidator.controltovalidate = "emailaddress1";
         newValidator.errormessage = "<a href='#emailaddress1_label' referencecontrolid='emailaddress1 ' onclick='javascript:scrollToAndFocus(\"emailaddress1 _label\",\" emailaddress1 \");return false;'>Email is a required field.</a>";
         newValidator.validationGroup = ""; // Set this if you have set ValidationGroup on the form
         newValidator.initialvalue = "";
         newValidator.evaluationfunction = function () {
            var contactMethod = $("#preferredcontactmethodcode").val();
            if (contactMethod != 2) return true; // check if contact method is not 'Email'.
            // only require email address if preferred contact method is email.
            var value = $("#emailaddress1").val();
            if (value == null || value == "") {
            return false;
            } else {
               return true;
            }
         };

         // Add the new validator to the page validators array:
         Page_Validators.push(newValidator);

      });
   }(window.jQuery));
}

一般驗證

按一下下一步/送出按鈕,就會執行名為 entityFormClientValidate 的函數。 您可以擴充這個方法來新增自訂驗證邏輯。

if (window.jQuery) {
   (function ($) {
      if (typeof (entityFormClientValidate) != 'undefined') {
         var originalValidationFunction = entityFormClientValidate;
         if (originalValidationFunction && typeof (originalValidationFunction) == "function") {
            entityFormClientValidate = function() {
               originalValidationFunction.apply(this, arguments);
               // do your custom validation here
               // return false; // to prevent the form submit you need to return false
               // end custom validation.
               return true;
            };
         }
      }
   }(window.jQuery));
}

另請參閱