說明:本文為《JavaScript高級程序設計》第11章“表單與數據完整性”學習筆記
一. 表單基礎
HTML表單是通過<form/>元素來定義的,它有以下特性:
method——表示瀏覽器發送GET請求或是發送POST請求;
action——表示表單所要提交到的地址URL;
enctype——當向服務器發送數據時,數據應該使用的編碼方法。默認是application/x-www-url-encoded,不過,如果要上傳文件,可以設置為multipart/form-data;
accept——當上傳文件時,列出服務器能正確處理的mime類型;
accept-charset——當提交數據時,列出服務器接受的字符編碼;
表單可以包含任意數量的輸入元素:
<input/>——主要的HTML輸入元素。通過type特性來判斷是哪種輸入控件:
text——單行文本框;
radio——單選按鈕;
checkbox——復選框
file——文件上傳文件框
password——密碼輸入框;
button——可用來產生自定義動作的一般按鈕;
submit——提交按鈕;
reset——重置按鈕;
hidden——不會出現在屏幕上的輸入字段;
image——圖像,與提交按鈕功能一樣。
<select/>:用來渲染組合框或者下拉列表框,里面的值由<option/>元素定義;
<textarea/>:渲染多行文本框,尺寸由rows和cols特性來確定。
二. 對<form/>元素進行腳本編寫
1. 獲取表單的引用
Eg1. var oForm = document.getElementById(“form1”);
Eg2. var oForm = document.forms[0]; //獲取第一個form
Eg3. var oForm = document.forms[“form1”]; //根據名稱
2. 訪問表單字段
Eg1. var oFirstField = oForm.elements[0]; // 獲取第一個表單元素
Eg2. var oTextbox1 = oForm.elements[“textbox1”]; //獲取名稱為textbox1的表單元素
Eg3. var oTextbox1 = oForm.textbox1; //獲取名稱為textbox1的表單元素
在名稱中有空格時,可以使用方括號標記:
var oTextbox1 = oForm[“text box 1”];
說明:也可以用document.getElementById()和表單字段的id來直接獲取元素。
3. 表單字段的共性
disabled特性可用來獲取或設置表單控件是否被禁用(被禁用的控件禁止用戶輸入);
form特性用來指向字段所在的表單;
blur()方法可以使表單字段失去焦點;
focus()可以使表單字段獲取焦點;
當字段失去焦點時,發生blur事件,執行onblur()事件處理函數;
當字段獲取焦點時,發生focus事件,執行onfocus()事件處理函數。
注意:隱藏字段只支持form特性。
4. 聚焦于第一個字段
可用如下代碼實現:
document.forms[0].elements[0].focus();
但這樣做還有點問題,如果表單的某個元素是隱藏字段,這個字段是不支持focus()方法的,這時候會出現JavaScript錯誤。我們需要的是將焦點放在第一個可見的表單字段上,可參考如下實現:
var FormUtil = new Object;
FormUtil.focusObject = function() {
if (document.forms.length > 0) {
for (var i=0; i<document.forms[0].elements.length; i++ ) {
var oField = document.forms[0].elements[i];
if (oField.type != “hidden”) {
oField.focus();
return;
}
}
}
}
調用舉例如下:
<body onload=”FormUtil.focusOnFirst()”>
5. 提交表單
在普通HTML中,必須使用提交按鈕或扮演提交按鈕角色的圖像來提交表單:
<input type=”submit” value=”提交” />
<input type=”image” src=”submit.gif” />
當用戶點擊其中一個按鈕,無需其他編碼,就可以提交表單。如果按回車鍵,并存在這些按鈕,瀏覽器就會認為是點擊了按鈕。
可以通過action特性中加入警告框來檢測表單是否已被提交:
<form method=”post” action=”javascript:alert(‘提交表單’)”>
還可以調用submit()方法提交表單:
Eg1. oForm.submit();
Eg2. <input type=”button” value=”提交” onclick=”document.forms[0].submit()” />
可以使用onsubmit()方法來檢查表單輸入的合法性:
<form method=”post” action=”javascript:alert(‘提交表單’)” onsubmit=”handleSubmit()”>
6. 僅提交一次
為防止表單多次提交,可使用如下方法:
將<input type=”submit” value=”提交”/>替換成:
<input type=” button” value=”提交” onclick=”this.disabled=true;this.form.submit()”/>
說明:不使用提交按鈕并用onclick()來禁用它的原因是,按鈕其實在表單提交前就已被禁用,這將導致表單不被提交。
7.重置表單
Eg1. <input type=”rest” value=”重置”/>
Eg2. <form method=”post” action=”javascript:alert(‘提交’)” onreset=”alert(‘正在重置’)” />
Eg3. <input type=”button” value=”重置” onclick=”document..forms[0].reset()” />
三. 文本框
Eg1. <input type=”text” size=”25” maxLength=”50” value=”阿蜜果” name=”nickName” />
Eg2. <textarea rows=”25” cols=”5”>文本值</textarea>
1. 獲取/更改文本框的值
eg1. var oTextbox1 = document.getElementById(“txt1”);
alert(oTextbox1.value);
alert(oTextbox1.value.length);
eg2. var oTextbox1 = document.getElementById(“txt1”);
oTextbox1.value = “hello,阿蜜果”;
2. 選擇文本
可使用select()方法,調用該方法前,文本框必須首先獲取焦點。參考代碼阿如下:
var oTextbox1 = document.getElementById(“txt1”);
oTextbox1.focus();
oTextbox1.select();
3. 文本框事件
blur——文本框失去焦點時觸發;
focus——文本框獲取焦點時觸發;
change——當用戶更改內容后文本框失去焦點時發生(如果是通過value特性來更改內容,則不會觸發);
select——當一個或多個字符被選中時發生,無論是手工選中還是用select()方法。
4. 選擇文本
Eg1. <input type=”text” onfocus=”this.select()” />
Eg2. <textarea onfocus=”this.select()”></textarea>
5. 自動切換到下一個
當某個文本框只允許接受指定數量的字符串時,常需要自動切換到下一個字段,讓我們來看看其實現:
FormUtil.tabForward = fuction(oTextbox) {
var oForm = oTextbox.form.
//確保該文本框不是表單的最后一個字段
if (oForm.elements[oForm.elements.length- 1] == oTextbox
&& oTextbox.value.length == oTextbox.getAttribute(“maxLength”)) {
for (var i=0; i<oForm.elements.length; i++) {
if (oForm.elements[i] == oTextbox) {
for (var j=i+1; j<oForm.elements.length; j++) {
if (oForm.elements[j].type != “hidden”) {
oForm.elements[j].focus();
return;
}
}
}
}
}
}
調用舉例:
<input type=”text” maxLength=”4” onkeyup=”FormUtil.tabForward(this)” />
6. 限制textarea的字符數
TextUtil.inNotMax = function(oTextarea) {
Return oTextarea.value.length = oTextarea.getAttribute(“maxlength”);
}
調用舉例如下:
<textarea rows=”10” cols=”25” maxlength=”150” onkeypress=”return TextUtil.isNotMax(this)”></textarea>
7. 允許/阻止文本框中的字符
1) 阻止無效的字符
TextUtil.blockChars = function(oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);
var sInvalidChars = oTextbox.getAttribute(“invalidchars”);
var sChar = String.fromCharCode(oEvent.charCode);
var bIsValidChar = sInvalidChars.indexOf(sChar) == -1;
return bIsValidChar || oEvent.ctrlKey;
};
調用舉例如下:
Eg1. <input type=”text” invalidchars = “0123456789” onkeypress=”return TextUtil.blockChars(this, event)” />;
Eg2. <textarea rows=”10” cols=”25” invalidchars = “0123456789” onkeypress=”return TextUtil.blockChars(this, event)” />;
2) 允許有效的字符
TextUtil.allowChars = function(oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);
var sValidChars = oTextbox.getAttribute(“validchars”);
var sChar = String.fromCharCode(oEvent.charCode);
var bIsValidChar = sInvalidChars.indexOf(sChar) > -1;
return bIsValidChar || oEvent.ctrlKey;
};
調用舉例如下:
Eg1. <input type=”text” validchars = “0123456789” onkeypress=”return TextUtil.allowChars (this, event)” />;
Eg2. <textarea rows=”10” cols=”25” validchars = “0123456789” onkeypress=”return TextUtil.allowChars (this, event)” />;
3) 不要忘記粘貼
用下面兩個方法來處理粘貼內容的驗證:
l 禁止粘貼
用戶可以通過兩種方法粘貼:通過點擊文本框上下文菜單的粘貼選項或按下Ctrl+V.
在IE中,可用onpaste方法解決,在其它瀏覽器中,可通過oncontextmenu事件處理函數解決,舉例如下:
<input type=”text” onkeypress=”return TextUtil.allowChars(this, event)” validChars=”0123456789” onpaste=”return false” oncontextmenu=”return false” />
要防止用戶按下Ctrl+V進行的粘貼,其實就是按下Ctrl和V,觸發keypress事件,修改allowChars()和blockChars()的最后一句為:
if (bBlockPaste) {
return bIsValidChar && !(oEvent.ctrlKey && sChar == ‘v’);
} else {
return bIsValidChar || oEvent.ctrlKey;
}
說明:其中bBlockPaste由函數作為參數傳入。
l 失去焦點時驗證
TextUtil.blurBlock = function(oTextbox) {
var sInvalidChars =oTextbox.getAttribute(“invalidchars”);
var arrInvalidChars = sInvalidChars.split(“”);
for (var i=0; i< arrInvalidChars.length; i++) {
if (oTextbox.value.indexOf(arrInvalidChars[i]) > -1) {
alert(“字符:” + arrInvalidChars[i] + “不允許輸入!”);
oTextbox.focus();
oTextbox.select();
return;
}
}
}
調用舉例如下:
<input type=”text” invalidchars = “0123456789” onkeypress=”return TextUtil.blockChars(this, event)” onblur=”TextUtil.blurBlock(this)” />;
8. 使用上下文按鍵操作數字文本
有時候我們想使用上下按鍵來增加和減少數字,為實現它,需要使用onkeydown事件處理函數。為了確保只是上下按鍵,要使用event的keyCode特性,上鍵的代碼是38,下鍵的是40,其他按鍵都回被忽略。下面來看實現這個功能的實現代碼:
TextUtil.numericScoll = function(oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);p
var iValue = oTextbox.value.length == 0 ? 0: parseInt(oTextbox.value);
var iMax = oTextbox.getAttribute(“max”);
var iMin = oTextbox.getAttribute(“min”);
if (oEvent.keyCode == 38) {
if (iMax == nul || iValue < parseInt(iMax)) {
oTextbox.value = (iValue + 1);
}
} else if (oEvent.keyCode == 40) {
if (iMin == nul || iValue < parseInt(iMin)) {
oTextbox.value = (iValue - 1);
}
}
};
調用舉例:
<input type=”text” onkeypress=”return TextUtil.allowChars(this, event)” vaidchars=”0123456789” onblur=”TextUtil.blurAllow(this)” onkeydown=”TextUtil.numericScroll(this, event)” max=”100” min=”0” />
四. 列表框和組合框
列表框和組合框都是通過HTML的<select/>元素來創建的。默認情況下,瀏覽器會將<select/>元素渲染成組合框。
Eg. <select name=”selAge” id=”selAge”>
<option value=”1”>18-21</option>
<option value=”2”>12-25</option>
<option value=”3”>16-29</option>
</select>
1. 訪問選項
Eg. var oListbox = document.forms[“form1”].selAge;
alert(oListbox.options[1].firstChild.nodeValue); //顯示text
alert(oListbox.options[1].getAttribute(“value”)); //顯示值
也可以用如下代碼阿實現:
alert(oListbox.options[1].text); //顯示text
alert(oListbox.options[1].value); //顯示值
alert(oListbox.options[1].index); //顯示1
alert(oListbox.options.length); //顯示列表長度
2.獲取/更改選中項
oListbox.selectedIndex顯示的是目前選中的選項的索引(如果沒有選中任何選項,那么為-1);
若<select/>中加上了屬性multiple=” multiple”時,存在選中多個選項的情況,可用如下方法來獲取選中的元素:
ListUtil.getSelectedIndexs = function(oListbox) {
var arrIndexes = new Array;
for (var i=0; i<oListbox.options.length; i++) {
if (oListbox.options[i].selected) {
arrIndexes.push(i);
}
}
return arrIndexes;
};
3.添加選項
ListUtil.add = function(oListbox, sName, sValue) {
var oOption = document.createElement(“option”);
oOption.appendChild(document.createTextNode(sName));
if (arguments.length == 3) {
oOption.setAttribute(“value”, sValue);
}
oListbox.appendChild(oOption);
}
4. 刪除選項
刪除列表中的某個選項,可用如下代碼:
ListUtil.remove = function(oListbox, iIndex) {
oListbox.remove(iIndex);
}
刪除列表中的所有選項:
ListUtil.clear = function(oListbox) {
for (int i=oListbox.options.length -1; i++) {
ListUtil.remove(oListbox, i);
}
}
5. 移動選項
ListUtil.move = function(oListboxFrom, oListboxTo, iIndex) {
var oOption = oListboxFrom.options[iIndex];
if (oOption != null) {
oListboxTo.append(oOption);
}
}
6. 重新排序選項
ListUtil.shiftUp = function(oListbox, iIndex) {
if (iIndex > 0) {
var oOption = oListbox.options[iIndex];
var oPrevOption = oListbox.options[iIndex - 1];
oListbox.insertBefore(oOption, oPrevOption);
}
}
ListUtil.shiftDown = function(oListbox, iIndex) {
if (iIndex > 0) {
var oOption = oListbox.options[iIndex];
var oNextOption = oListbox.options[iIndex + 1];
oListbox.insertBefore(oNextOption , oOption);
}
}
五. 創建自動提示的文本框
1. 匹配
TextUtil.autosuggestMatch = function(sText, arrValues) {
var arrResult = new Array;
if (sText != “”) {
for (var i=0; i<arrValues.length; i++) {
if (arrValues[i].indexOf[sText] == 0) {
arrResult.push[arrValues[i]];
}
}
}
return arrResult;
}
2. 內部機制
TextUtil.autosuggest = function(oTextbox, arrValues, sListboxId) {
var oListbox = document.getElementById(sListboxId);
ListUtil.clear(oListbox);
var arrMatches = TextUtil.autosuggestMatch(oTextbox.value, arrValues);
for(int i=0; i<arrMatchs.length; i++) {
ListUtil.add(oListbox, arrMatchs[i]);
}
};
說明:本節中描述的自動提示功能是區分大小寫的。如果要進行大小寫不區分的比較,需將數組中的所有值轉換為小寫并與轉換為小寫的文本框中的值進行比較。
posted on 2007-08-20 08:35
阿蜜果 閱讀(2615)
評論(3) 編輯 收藏