DIV CSS 佈局教程網

JavaScript 表單操作完整總結:視窗、驗證、動態列與取值
編輯:JavaScript綜合知識     

表單相關的 JavaScript 操作散落在各種小技巧裡,做久了容易忘。這篇把常用手法整理成一份可查閱的清單,涵蓋視窗控制、快取設定、元素啟停、動態表格與常見驗證。

一、視窗與重新整理

window.location.reload();                    // 重新整理目前頁
window.opener.location.reload();             // 重新整理父視窗(由彈出視窗呼叫)
window.dialogArguments.location.reload();    // 重新整理 showDialog 的呼叫者

二、開啟螢幕置中的視窗

// 以 window.open 實作置中
function ShowDialog(url) {
    var iWidth = 300, iHeight = 200;
    var iTop  = (window.screen.height - iHeight) / 2;
    var iLeft = (window.screen.width  - iWidth)  / 2;
    window.open(url, "Detail", "Scrollbars=no,Toolbar=no,Location=no,"
        + "Width=" + iWidth + ",Height=" + iHeight
        + ",top=" + iTop + ",left=" + iLeft);
}

// 以 showModalDialog 實作置中
function ShowDialog(url) {
    var iWidth = 300, iHeight = 200;
    var iTop  = (window.screen.height - iHeight) / 2;
    var iLeft = (window.screen.width  - iWidth)  / 2;
    window.showModalDialog(url, window,
        "dialogHeight: " + iHeight + "px; dialogWidth: " + iWidth + "px;"
        + "dialogTop: " + iTop + "; dialogLeft: " + iLeft
        + "; resizable: no; status: no; scroll: no");
}

三、關閉頁面快取(JSP)

<%
response.setHeader("Pragma", "No-Cache");
response.setHeader("Cache-Control", "No-Cache");
response.setDateHeader("Expires", 0);
%>

四、無提示關閉視窗

function CloseWin(){
    var ua = navigator.userAgent;
    var ie = navigator.appName == "Microsoft Internet Explorer";
    if (ie) {
        var IEversion = parseFloat(ua.substring(ua.indexOf("MSIE ") + 5,
                            ua.indexOf(";", ua.indexOf("MSIE "))));
        if (IEversion < 5.5) {
            document.body.insertAdjacentHTML("beforeEnd",
                '<object id="noTipClose" classid="{...}"></object>');
            document.all.noTipClose.Click();
        } else {
            window.opener = null;   // 關鍵:解除開啟者關係才能無警告關閉
            window.close();
        }
    } else {
        window.close();
    }
}

五、定時關閉與清除計時器

function closeit(){
    setTimeout("self.close()", 100000);   // 單位為毫秒
    // setInterval("self.close()", 100000);
}
window.clearTimeout(me.timer);
window.clearInterval(me.timer);

六、透過 URL 傳值給子視窗

function fn_modify(pid){
    var ModifyInfo = new Object();
    window.showModalDialog("modify_main.asp?pid=" + pid, ModifyInfo,
        "dialogHeight:180px;dialogWidth:300px;resizable:off;center:on;help:off;scroll:off;status:off");
    Reload();
}
function Reload(){ location.href = "abc.asp"; }
</script>
<a href="abc.asp" onClick="fn_modify('這是值')">單擊</a>

七、隱藏/顯示與啟停元素

// 顯示/隱藏
document.getElementById("bt").style.display = "none";  // 隱藏
document.getElementById("bt").style.display = "";      // 顯示

// 啟用/停用
document.getElementById("bt").disabled = true;   // 失效
document.getElementById("bt").disabled = false;  // 生效

// 設定/讀取 innerHTML
document.getElementById("labTitle").innerHTML = "IP模式";
var t = document.getElementById("labTitle").innerHTML;

// 切換 disabled 並同步改字
<input id="mytext" type="text" value="我是能用的">
<input type="button" value="disable"
  onclick="if (mytext.disabled == false){ mytext.disabled = true;
    mytext.value = '我是不能用的'; this.value = 'enable'; }
    else { mytext.disabled = false; mytext.value = '我是能用的'; this.value = 'disable'; }">

八、以函式提交表單

function exit(){
    selcardForm.action = "/NDHotel/queryTroom.do?method=exitSystem";
    selcardForm.submit();
}

九、遍歷 radio 取得選中值

var radios = document.getElementsByName("workMode");
var workMode = "";
for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked == true) {
        workMode = radios[i].value;
    }
}

十、動態為 select 加入 option

var prov = document.getElementById("ddlProvince");
prov.options.add(new Option("---請選擇---", ""));

var pArray = zoneIdProvince.split("&");
for (var i = 0; i < pArray.length; i++) {
    var idpArray = pArray[i].split("#");
    prov.options.add(new Option(idpArray[1], idpArray[0]));
}

十一、動態新增與移除表格列

var autoId = 0;
function addRow(value1, value2){
    var highQuery = document.getElementById("tdSearch");
    highQuery.insertRow();
    var newRow = highQuery.rows[highQuery.rows.length - 1];
    newRow.id = "row_" + autoId;

    newRow.insertCell();
    newRow.cells[0].innerHTML =
        "<input value='" + value1 + "' onchange='changeip(" + autoId + ")' type='text' id='bIPFrom_" + autoId + "'>-";

    newRow.insertCell();
    newRow.cells[1].innerHTML =
        "<input value='" + value2 + "' type='text' id='bIPTo_" + autoId + "'>";

    var cell2 = newRow.insertCell();
    cell2.innerHTML = "<input type='button' value='-' onClick=removeRow('" + newRow.id + "')>";
    autoId++;
}
function removeRow(rowId){
    var trRow = document.getElementById(rowId);
    trRow.removeNode(true);   // 舊 IE 語法,標準寫法為 trRow.remove()
}

十二、焦點與取值

var v = document.getElementById("lindex").value;
document.getElementById("lindex").focus();
document.getElementById("lindex").blur();

document.getElementById("txt_AutoTime").readOnly = true;
document.getElementById("txt_AutoTime").style.backgroundColor = "#d0d0d0";
runParamSetForm.radNotForcibly.checked = true;

十三、IP 位址格式驗證

function ipCheck(ipValue){
    var reg = /^\d{1,3}(\.\d{1,3}){3}$/;
    if (ipValue != "") {
        if (reg.test(ipValue)) {
            var ary = ipValue.split('.');
            for (var key in ary) {
                if (parseInt(ary[key]) > 255) return false;
            }
            return true;
        } else {
            return false;
        }
    }
    return true;
}

使用提醒

這份清單中的部分寫法帶有明顯的時代痕跡:document.all、removeNode、以字串形式傳給 setTimeout 的第一個參數,以及 for...in 搭配 parseInt 的做法,都不建議在新專案沿用。取值請統一用 document.getElementById 或 querySelector,移除節點用 remove(),計時器請直接傳函式參照而非字串。另外用 for...in 遍它有原型鏈上的可列舉屬性風險,改為 ary.forEach() 或 for...of 更穩妥。把觀念留下、語法更新,這份總結才能真正發揮價值。

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