首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET DropDownList 客戶端變更偵測:JavaScript 記錄初始值避免誤提示

     編輯:ASP.NET 基礎

場景

編輯頁面中 DropDownList 綁定重要屬性,需在使用者真正修改值時才彈出提醒,若改回原值則不提示。

解決思路

  1. window.onload 取得載入後的初始選項文字存入變數。
  2. onchange 事件比較目前選項與初始值,不同才提示。

完整實作

後台註冊事件


DDLmaterial.Attributes.Add("onchange", "changeAlert()");

前端 JavaScript


<script type="text/javascript">
    var firstText = "";
    var ddl = null;

    window.onload = function() {
        ddl = document.getElementById('DDLmaterial');
        firstText = ddl.options[ddl.selectedIndex].text;
    }

    function changeAlert() {
        var currentText = ddl.options[ddl.selectedIndex].text;
        if (currentText !== firstText) {
            alert("注意:您修改了物品類型!");
        }
    }
</script>

關鍵點解析

  • window.onload 確保 DOM 就緒再取元素,避免 null 錯誤。
  • options[selectedIndex].text 取得顯示文字而非 value,視業務需求二擇一。
  • 變數提升至全域作用域,供 changeAlert 存取。

VS 2008+ 智能提示加持

Visual Studio 2008 起支援 JavaScript IntelliSense,大幅降低前端開發門檻,善用它!

延伸:若有多個 DropDownList


var initialValues = {}; // key: ClientID, value: initial text

window.onload = function() {
    var ddls = document.querySelectorAll('select[id$="DDL"]'); // 依命名慣例抓取
    ddls.forEach(function(ddl) {
        initialValues[ddl.id] = ddl.options[ddl.selectedIndex].text;
        ddl.onchange = function() {
            if (this.options[this.selectedIndex].text !== initialValues[this.id]) {
                alert("欄位 " + this.id + " 已變更!");
            }
        };
    });
};

統一管理,擴展性佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved