編輯頁面中 DropDownList 綁定重要屬性,需在使用者真正修改值時才彈出提醒,若改回原值則不提示。
window.onload 取得載入後的初始選項文字存入變數。onchange 事件比較目前選項與初始值,不同才提示。
DDLmaterial.Attributes.Add("onchange", "changeAlert()");
<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 存取。Visual Studio 2008 起支援 JavaScript IntelliSense,大幅降低前端開發門檻,善用它!
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 + " 已變更!");
}
};
});
};
統一管理,擴展性佳。