js筆記--表單

鬆鬆個人網絡日誌

1.表單基礎知識

JS中表單類型是:HTMLFormElement。繼承 HTMLElement。和其他HTML元素有相同的屬性。獨有屬性如下:
  • acceptCharset:服務器能處理的字符集;等價於HTML中的accept-charset特性
  • action:接收請求的URL;等價於HTML中的action特性
  • elements:表單中所有控件的集合(HTMLCollection)
  • enctype:請求的編碼類型;等價於HTML中的enctype特性
  • length:表單中控件的數量
  • method:http請求類型,get或post
  • name:表單名
  • reset():重置表單
  • submit():提交表單
  • target:發送請求和接收響應的窗口名稱
獲取form表單:
一:document.getElementById("id");

二:document.forms[0] 或  document.forms["formname"]

1.提交表單

	<!-- 通用提交按鈕-->
	<input type="submit" value="submit">
	<button type="submit">submit</button>
	<!--圖像按鈕提交表單-->
	<input type="image" src="flag.png">
提交表單時,瀏覽器會在將請求發送給服務器之前觸發submit事件。可以在事件處理程序中驗證表單數據。阻止事件的默認行爲可以取消表單提交。
	var form = document.forms["myform"];
	console.log(form);
	EventUtil.addHandler(form,"submit",function(event){
		console.log(event);
		//取消表單提交
		event.preventDefault();
	});
	//直接調用submit()方法提交表單。不會觸發submit事件
	form.submit();
表單重複提交問題:解決方法,在第一次提交表單後禁用提交按鈕。或利用onsubmit事件處理程序取消後續的表單提交操作

2.重置表單

使用type特性值爲"reset"的<input>或<button>都可以創建重置按鈕。

	<input type="reset" value="重置">
	<button type="reset">重置</button>

重置會觸發reset事件,可以在事件處理程序中取消重置

	var form1 = document.forms["myform"];
	EventUtil.addHandler(form1,"reset",function(event){
		//阻止reset事件默認行爲
		event.preventDefault();
	});
form.reset()方法重置表單會觸發reset事件

3.表單字段

每個表單都有elements屬性,該屬性是表單中所有元素的集合(<input>,<textarea>,<button>,<fieldset>)。這個集合是一個有序列表,每個表單字段在集合中的順序就是它們出現在標記中的順序。可按照位置和name特性來訪問它們。

	var form1 = document.forms["myform"];
	//獲取表單中的第一個字段
	var field1 = form1.elements[0];
	//根據屬性名獲取表單元素
	var field2 = form1.elements["username"];

	var fieldCount = form1.elements.length;
	console.log(field1);
	console.log(field2);
	console.log(fieldCount);

1.共有的表單字段屬性

除了<fieldset>元素之外,所有表單字段都擁有相同的一組屬性。

  • disabled:表示當前字段是否被禁用
  • form:指向當前字段所屬表單的指針;只讀
  • name:字段名稱
  • readOnly:只讀
  • tabIndex:當前字段的切換(tab)序號
  • type:當前字段的類型
  • value:當前字段提交給服務器的值。對文件字段來說,這個屬性是隻讀的
	var form1 = document.forms["myform"];
	var field1 = form1.elements[0];
	var fields = form1.elements;
	console.log(field1.form === form1); //true

	//監聽表單提交事件
	EventUtil.addHandler(form1,"submit",function(event){
		var submitForm = event.target;
		var btn = submitForm.elements["submit_btn"];
		//提交表單時讓提交按鈕不可用
		btn.disabled = true;
		event.preventDefault();
	});

2.公有的表單字段方法

focus()和blur()

頁面加載完後焦點移到第一個字段  html5   autofocus屬性,布爾值,自動聚焦。

	EventUtil.addHandler(window,"load",function(){
		var element = document.forms[0].elements[0];
		if(element.autofocus !== true){
			element.focus();
		}
	});

3.共有表單字段事件

blur:

change:

focus:

2.文本框腳本

<input type="text" size="25" maxlength="50">

1.選擇文本

獲取焦點時選中文本內容
	var username = document.forms[0].elements["username"];
	EventUtil.addHandler(username,"focus",function(event){
		event.target.select();
	});
	//選擇事件
	EventUtil.addHandler(username,"select",function(event){
		console.log("selected");
	});

2.獲取選擇的文本

	//選擇事件
	EventUtil.addHandler(username,"select",function(event){
		console.log(username.value.substring(username.selectionStart,username.selectionEnd));
	});

3.選擇部分文本

2.過濾輸入

1.屏蔽字符

	var username = document.forms[0].elements["username"];
	EventUtil.addHandler(username,"keypress",function(event){
		var charCodeStr = String.fromCharCode(event.charCode);
		console.log(charCodeStr);
		//如果是非數字,且不是向上向下,空格等鍵,沒有按下Ctrl鍵(複製,粘貼)
		if(!/\d/.test(charCodeStr)&&event.charCode>9&&!event.ctrlKey){
			event.preventDefault();
		}
	});

2.自動切換焦點

//當前文本框輸入完成後自懂焦點切換到下一個元素
	(function(){
		function tabForward(event){
			var target = event.target;
			//如果輸入完成
			if(target.value.length == target.maxLength){
				var form = target.form;
				for(var i=0;i<form.elements.length;i++){
					if(form.elements[i] == target){
						if(form.elements[i+1]){
							form.elements[i+1].focus();
						}
						return;
					}
				}
			}
		}
		var text = document.forms[0].elements["username"];
		EventUtil.addHandler(text,"keyup",tabForward);
	})();

3.html5約束驗證

1.必填字段  required
<input name="username" type="text" value="hehe" maxlength="3" required>
2.其他輸入類型
	<input name="email" type="email">
	<input name="url" type="url">
3.輸入模式  pattern
接收正則表達式
<input name="username1" type="text" pattern="\d+">
4.檢測有效性
checkValidity()檢測表單中的某個字段是否有效
	var form = document.forms[0];
	form.checkValidity();//表單所有元素驗證通過才返回true
	EventUtil.addHandler(form,"submit",function(event){
		var username = document.forms[0].elements["username"];
		if(username.checkValidity()){
			//有效
			console.log("正確");
			event.preventDefault();
		}else{
			//無效,表單不提交
			console.log("錯誤");
			event.preventDefault();
		}
	});
5.禁用腳本
通過設置表單的novalidate屬性
如果表單有多個提交按鈕,可以指定某個提交按鈕不驗證表單。通過在按鈕上添加formnovalidate屬性。
	var form = document.forms[0];
	form.novalidate = true;//禁用驗證

3.選擇框腳本

  • add:添加新<option>元素
  • multiple:是否多選項
  • options:<option>元素的HTMLCollection集合
  • remove(index):移除指定位置的選項
  • selectedIndex:選中項的索引
  • size:選擇框中可見的行數
<option>選項屬性
  • index:當前選項在options集合中的索引
  • label:當前選項的標籤
  • selected:是否選中,設置爲true時可以選中噹噹前選項
  • text:選項的文本
  • value:選項的值
選中了選項就會觸發選擇框的change事件

1.選擇選項

		var selectbox = document.forms[0].elements[0];

		EventUtil.addHandler(selectbox,"change",function(event){
			for(var i=0;i<selectbox.options.length;i++){
				var option = selectbox.options[i];
				if(option.selected){
					console.log(option.value+"  "+option.text);	

				}
			}
		});

2.添加選項

方式一:
		var selectbox = document.forms[0].elements[0];

		var option = document.createElement("option");
		option.value="5";
		option.text = "sun qi";
		selectbox.appendChild(option);
方式二:使用Option構造函數來創建新選項
		var option1 = new Option("qianba","6");
		selectbox.appendChild(option1);

方式三:使用選擇框的add()方法,接收兩個參數,一:添加的選項。二:位於新選項後的選項。跨瀏覽器在最後添加選項,第二個參數給undefined

		var selectbox = document.forms[0].elements[0];
		var option = new Option("ethan","5");
		selectbox.add(option,undefined);//最佳方案

3.移除選項

使用DOM的 removeChild()

選擇框的remove(index)方法

		selectbox.removeChild(selectbox.options[0]);
		selectbox.remove(0);

4.移動和重排選項

移動和移除選項都會重置每個選項的index屬性

insertBefore();在指定元素前插入要移動的選項

		var optionToMove = selectbox.options[0];
		selectbox.insertBefore(optionToMove,selectbox.options[optionToMove.index + 2]);

4.表單序列化

瀏覽器提交表單數據過程:
  • 對錶單字段的名稱和值進行URL編碼,使用&符分隔
  • 不發送禁用的表單字段
  • 只發送勾選的複選框和單選按鈕
  • 不發送type爲"reset"和"button"的按鈕
  • 多選框中的每個選中的值單獨一個條目
  • 在單擊提交按鈕提交表單時,也會發送提交按鈕;否則不發送提交按鈕。包括type爲"image"的input元素
  • select元素的值就是選中的選項的value值,如果沒有value就爲文本值
表單序列化代碼:
		function serialize(form){
			var parts = [],  //要提交的數據
				field = null,
				i,
				len,
				j,
				optLen,
				option,
				optValue;
			//遍歷表單元素
			for(i=0;i<form.elements.length;i++){
				field = form.elements[i];
				//判斷表單元素類型
				switch(field.type){
					//選擇框類型
					case "select-one":
					case "select-multiple":
						if(field.name.length){//如果字段名存在
							for(j=0,optLen = field.options.length;j<optLen;j++){//遍歷選擇框的所有選項
								option = field.options[j];
								if(option.selected){//被選中
									optValue = '';
									if(option.hasAttribute){//支持hasAttribute方法獲取屬性
										//有value屬性就返回value的值,沒有就返回文本值
										optValue = (option.hasAttribute("value")?option.value:option.text);		
									}else{
										optValue = (option.attributes["value"].specified?option.value:option.text);
									}
									//數組中添加要提交的數據字符串
									parts.push(encodeURIComponent(field.name)+"="+encodeURIComponent(optValue));
								}
							}
						}
						break;
					case undefined:  //字段集
					case "file":  //文件輸入
					case "submit":
					case "reset":
					case "button": //自定義按鈕
						break;
					case "radio":  //單選
					case "checkbox":  // 多選
						if(!field.checked){//爲選中
							break;
						}
					default:
						//字段名稱存在的元素
						if(field.name.length){
							parts.push(encodeURIComponent(field.name)+"="+encodeURIComponent(field.value));
						}
				}
			}
			return parts.join("&");//返回表單要提交的內容
		}

DOM兼容的瀏覽器中使用hasAttribute()來獲取屬性值,IE中使用specified屬性來判斷

如果表單中包含<fieldset>元素,該元素會出現在元素集合中,type屬性不存在。因此,如果type屬性未定義,就不需要對其進行序列化。

5.富文本編輯

WYSIWYG(What you see is what you get,所見即所得)。在頁面中嵌入一個包含空HTML頁面的iframe。通過設置designMode屬性來使HTML頁面可以被編輯。編輯元素就是該頁面<body>元素的HTML代碼。designMode屬性默認值"off", “on”表示可編輯。
			EventUtil.addHandler(window,"load",function(){
				var frame = window.frames["richedit"];
				frame.document.designMode = "on";
			});
		</script>
	<body>
		<iframe name="richedit" src="h2.html" style="width:300px;height:300px;" />

1.使用contenteditable屬性

<div id="editDiv" contenteditable>hehe</div>

屬性可以給頁面中任何元素使用(使該元素可編輯)

		var div = document.getElementById("editDiv");
		div.contentEditable = "true";
		div.contentEditable = "false";
true:打開。false:關閉。inherit:從父元素那裏繼承

2.操作富文本

document.execCommand()方法可以對文檔執行預定義的命令。
3個參數:一,要執行的命令名稱;二,瀏覽器是否提供界面(false);三,執行命令必須的值(不需要值就傳遞null)
	EventUtil.addHandler(window,"load",function(){
		var richEditFrame = window.frames["richEdit"];
		richEditFrame.document.designMode  = "on";
		richEditFrame.document.execCommand("bold",false,null);
		richEditFrame.document.execCommand("createlink",false,"http://www.baidu.com");
		var div = document.getElementById("editDiv");
		div.contentEditable = "true";
		document.execCommand("bold",false,null);
	});

3.表單與富文本

由於富文本編輯是使用iframe而非表單控件實現的。要提交富文本編輯中的內容,需要我們手工提取並提交HTML。通常添加一個隱藏字段,在表單提交前,將從iframe中提取的HTML賦值給隱藏字段。

	EventUtil.addHandler(document.forms[0],"submit",function(){
		 document.forms[0].elements["comments"].value = window.frames["richEdit"].document.body.innerHTML;
	});

小結:
  • 在文本框內容變化時,可以監聽鍵盤事件來檢查插入的字符,從而允許或禁止用戶輸入某些字符

鬆鬆個人網絡日誌

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章