DIV CSS 佈局教程網

使用原生 JavaScript 建立通用表單驗證提示
編輯:關於JavaScript     

表單驗證常需要在輸入框旁即時顯示錯誤訊息。利用原生 DOM,可以動態建立提示元素,不必在 HTML 中預先放置大量 span 或 label。

驗證函式

checkResult 接收條件、參考元素 id 與提示文字。當條件成立時顯示訊息,不成立時清空訊息。

function checkResult(checkCondition, showAfterId, showMsg) {
  var showLabelId = showAfterId + 'showMsg';
  if (checkCondition) {
    if (document.getElementById(showLabelId)) {
      document.getElementById(showLabelId).innerHTML = showMsg;
    } else {
      createShowElement(showAfterId, showLabelId, 'color:red', showMsg, 'span');
    }
  } else {
    var el = document.getElementById(showLabelId);
    if (el) el.innerHTML = '';
  }
}

動態建立提示元素

function createShowElement(currentId, elementId, style, showMsg, tagName) {
  if (!tagName) tagName = 'label';
  var currentDom = document.getElementById(currentId);
  var showMsgDom = document.createElement(tagName);
  if (style) showMsgDom.setAttribute('style', style);
  showMsgDom.setAttribute('id', elementId);
  showMsgDom.innerHTML = showMsg;
  currentDom.parentNode.insertBefore(showMsgDom, currentDom.nextSibling);
}

這種做法讓驗證邏輯集中,易於擴充。實務上也可進一步封裝為物件,統一管理規則、訊息與顯示位置。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved