posts - 297,  comments - 1618,  trackbacks - 0
           

          說明:本文為《JavaScript高級程序設計》第11章“表單與數(shù)據(jù)完整性”學習筆記

          一.  表單基礎

           HTML表單是通過<form/>元素來定義的,它有以下特性:

              method——表示瀏覽器發(fā)送GET請求或是發(fā)送POST請求;

              action——表示表單所要提交到的地址URL

              enctype——當向服務器發(fā)送數(shù)據(jù)時,數(shù)據(jù)應該使用的編碼方法。默認是application/x-www-url-encoded,不過,如果要上傳文件,可以設置為multipart/form-data

              accept——當上傳文件時,列出服務器能正確處理的mime類型;

              accept-charset——當提交數(shù)據(jù)時,列出服務器接受的字符編碼;

           

          表單可以包含任意數(shù)量的輸入元素:

          <input/>——主要的HTML輸入元素。通過type特性來判斷是哪種輸入控件:

              text——單行文本框;

              radio——單選按鈕;

             checkbox——復選框

              file——文件上傳文件框

              password——密碼輸入框;

              button——可用來產(chǎn)生自定義動作的一般按鈕;

              submit——提交按鈕;

              reset——重置按鈕;

              hidden——不會出現(xiàn)在屏幕上的輸入字段;

              image——圖像,與提交按鈕功能一樣。

           

          <select/>:用來渲染組合框或者下拉列表框,里面的值由<option/>元素定義;

          <textarea/>:渲染多行文本框,尺寸由rowscols特性來確定。

          二.  <form/>元素進行腳本編寫

          1. 獲取表單的引用

          Eg1. var oForm = document.getElementById(“form1”);

          Eg2. var oForm = document.forms[0]; //獲取第一個form

          Eg3. var oForm = document.forms[“form1”]; //根據(jù)名稱

          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()可以使表單字段獲取焦點;

              當字段失去焦點時,發(fā)生blur事件,執(zhí)行onblur()事件處理函數(shù);

              當字段獲取焦點時,發(fā)生focus事件,執(zhí)行onfocus()事件處理函數(shù)。

          注意:隱藏字段只支持form特性。

          4. 聚焦于第一個字段

          可用如下代碼實現(xiàn):

          document.forms[0].elements[0].focus();

          但這樣做還有點問題,如果表單的某個元素是隱藏字段,這個字段是不支持focus()方法的,這時候會出現(xiàn)JavaScript錯誤。我們需要的是將焦點放在第一個可見的表單字段上,可參考如下實現(xiàn):

          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;

          }

          }

          }

          }

          調(diào)用舉例如下:

          <body onload=”FormUtil.focusOnFirst()”>

          5. 提交表單

           在普通HTML中,必須使用提交按鈕或扮演提交按鈕角色的圖像來提交表單:

           <input type=”submit” value=”提交” />

           <input type=”image” src=”submit.gif” />

           當用戶點擊其中一個按鈕,無需其他編碼,就可以提交表單。如果按回車鍵,并存在這些按鈕,瀏覽器就會認為是點擊了按鈕。

           可以通過action特性中加入警告框來檢測表單是否已被提交:

           <form method=”post” action=”javascript:alert(‘提交表單’)”>

           還可以調(diào)用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()方法,調(diào)用該方法前,文本框必須首先獲取焦點。參考代碼阿如下:

          var oTextbox1 = document.getElementById(“txt1”);

          oTextbox1.focus();

          oTextbox1.select();

          3.       文本框事件

             blur——文本框失去焦點時觸發(fā);

             focus——文本框獲取焦點時觸發(fā);

             change——當用戶更改內(nèi)容后文本框失去焦點時發(fā)生(如果是通過value特性來更改內(nèi)容,則不會觸發(fā));

             select——當一個或多個字符被選中時發(fā)生,無論是手工選中還是用select()方法。

          4.       選擇文本

          Eg1. <input type=”text” onfocus=”this.select()” />

          Eg2. <textarea onfocus=”this.select()”></textarea>

          5.       自動切換到下一個

          當某個文本框只允許接受指定數(shù)量的字符串時,常需要自動切換到下一個字段,讓我們來看看其實現(xiàn):

          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;

          }

          }

          }

          }

          }

          }

           調(diào)用舉例:

           <input type=”text” maxLength=”4” onkeyup=”FormUtil.tabForward(this)” />

          6.       限制textarea的字符數(shù)

          TextUtil.inNotMax = function(oTextarea) {

          Return oTextarea.value.length = oTextarea.getAttribute(“maxlength”);

          }

          調(diào)用舉例如下:

          <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;

          };

          調(diào)用舉例如下:

          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;

          };

          調(diào)用舉例如下:

          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) 不要忘記粘貼

          用下面兩個方法來處理粘貼內(nèi)容的驗證:

          l         禁止粘貼

          用戶可以通過兩種方法粘貼:通過點擊文本框上下文菜單的粘貼選項或按下Ctrl+V.

          IE中,可用onpaste方法解決,在其它瀏覽器中,可通過oncontextmenu事件處理函數(shù)解決,舉例如下:

          <input type=”text” onkeypress=”return TextUtil.allowChars(this, event)” validChars=”0123456789” onpaste=”return false” oncontextmenu=”return false” />

          要防止用戶按下Ctrl+V進行的粘貼,其實就是按下CtrlV,觸發(fā)keypress事件,修改allowChars()blockChars()的最后一句為:

          if (bBlockPaste) {

              return bIsValidChar && !(oEvent.ctrlKey && sChar == ‘v’);

          } else {

              return bIsValidChar || oEvent.ctrlKey;

          }

          說明:其中bBlockPaste由函數(shù)作為參數(shù)傳入。

          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;

          }

          }

          }

          調(diào)用舉例如下:

          <input type=”text” invalidchars = “0123456789” onkeypress=”return TextUtil.blockChars(this, event)”  onblur=”TextUtil.blurBlock(this)” />;

          8.       使用上下文按鍵操作數(shù)字文本

          有時候我們想使用上下按鍵來增加和減少數(shù)字,為實現(xiàn)它,需要使用onkeydown事件處理函數(shù)。為了確保只是上下按鍵,要使用eventkeyCode特性,上鍵的代碼是38,下鍵的是40,其他按鍵都回被忽略。下面來看實現(xiàn)這個功能的實現(xiàn)代碼:

          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);

          }

          }

          };

          調(diào)用舉例:

          <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/>元素來創(chuàng)建的。默認情況下,瀏覽器會將<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”)); //顯示值

             也可以用如下代碼阿實現(xiàn):

             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);

          }

          }

           

          五.             創(chuàng)建自動提示的文本框

          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.       內(nèi)部機制

          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]);

          }

          };

          說明:本節(jié)中描述的自動提示功能是區(qū)分大小寫的。如果要進行大小寫不區(qū)分的比較,需將數(shù)組中的所有值轉(zhuǎn)換為小寫并與轉(zhuǎn)換為小寫的文本框中的值進行比較。

          posted on 2007-08-20 08:35 阿蜜果 閱讀(2617) 評論(3)  編輯  收藏


          FeedBack:
          # re: JavaScript學習筆記——表單與數(shù)據(jù)完整性
          2007-08-21 14:19 | Thomas
          這個系列,我很滿意!
          o(∩_∩)o...哈哈  回復  更多評論
            
          # re: JavaScript學習筆記——表單與數(shù)據(jù)完整性
          2007-08-21 21:24 | 阿蜜果
          @Thomas
          喜歡就好!
          嘿嘿  回復  更多評論
            
          # re: JavaScript學習筆記——表單與數(shù)據(jù)完整性[未登錄]
          2007-08-21 22:14 | june
          最近隔三差五就上來你這里看看。功力沒你深厚,哈哈……
          你很勤快,我很喜歡。  回復  更多評論
            

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          <2007年8月>
          2930311234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

                生活將我們磨圓,是為了讓我們滾得更遠——“圓”來如此。
                我的作品:
                玩轉(zhuǎn)Axure RP  (2015年12月出版)
                

                Power Designer系統(tǒng)分析與建模實戰(zhàn)  (2015年7月出版)
                
               Struts2+Hibernate3+Spring2   (2010年5月出版)
               

          留言簿(263)

          隨筆分類

          隨筆檔案

          文章分類

          相冊

          關注blog

          積分與排名

          • 積分 - 2296376
          • 排名 - 3

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 泗洪县| 鲜城| 吴江市| 靖宇县| 咸丰县| 永胜县| 泾川县| 绵竹市| 积石山| 上杭县| 邯郸县| 凌源市| 茌平县| 彩票| 马鞍山市| 贵定县| 安塞县| 仪征市| 江都市| 辽宁省| 江陵县| 康马县| 望谟县| 确山县| 禹城市| 光泽县| 长阳| 甘肃省| 平乐县| 胶南市| 宿迁市| 广南县| 无棣县| 保山市| 武平县| 陆丰市| 石林| 密山市| 江永县| 奉节县| 松桃|