iT邦幫忙

0

【物件導向】表單驗證 - javascript系列課程Days-3 (Api-插件開發)-(無需依賴jQuery)

作者:pratnket
版本:2017_Var1

javascript系列課程Days-1
javascript系列課程Days-2
javascript系列課程Days-3

使用頁

<html>

<head>

<script src="Verificat.js"></script>

<script>
function log(msg) {
	if( window.console ) {
		console.log(msg);
	}
}

//使用方式,自訂DOM名稱

//入口
function ck(name) {
	return document.getElementById(name);
}

//入口
function $(name) {
	return document.getElementById(name);
}

window.onload = function() {

	//簡易用法
	//onclick="Verificat.Form()"
	
	//程式用法--(sub) = Submit 的 name
	//程式用法-- ck 函式
	/*
    ck("sub").onclick = function() {
		//檢查表單
		Verificat.Form();
		//Verificat.result() 呼叫判斷結果
		if(  Verificat.result() == true  )  alert("表單驗證成功");
		if(  Verificat.result() == false )  alert("表單驗證失敗");
    };
	*/
	//我用JQ的符號測試
    $("sub").onclick = function() {
		//檢查表單
		Verificat.Form();
		//Verificat.result() 呼叫判斷結果
		if(  Verificat.result() == true  )  alert("表單驗證成功");
		if(  Verificat.result() == false )  alert("表單驗證失敗");
    };
	
};


</script>

</head>

<body>

<form id="Form">

	數值1: <input id="fname" type="text" value="Mickey" />
	數值2: <input id="lname" type="text" value="Mouse" required="" />
	數值3: <input id="lname2" type="text" value="Mouse" required="" />
	數值4: <input id="lname3" type="text" value="Mouse" required="" />
	
	<input id="sub" name="sub" type="button" value="Submit"/>


</form>

</body>
</html>

JS頁

(function () {
	//預設值
	var options = {
		Form: 'Form',
		Placeholder: '請填寫入數值',
		Style: 'background-color:powderblue',
		Msg: '你尚有內容未填寫',
		Bool: true,
	}

	//API
	var api = {
		//修改預設值
		config: function (opts) {
			if(!opts) return options;
			for(var key in opts) {
				options[key] = opts[key];
			}
			return this;
		},
		
		
		
		Form: function Form() {
			var result = options.Bool;
			var x = document.getElementById(options.Form);
			for (var i=0 ; i < x.length ; i++){		
				if(x.elements[i].required){
					if (x.elements[i].value==null || x.elements[i].value=="")
					{
						x.elements[i].style = options.Style;
						x.elements[i].placeholder = options.Placeholder;
						var result = false;
					}	
				}
			}		 
			//result || (alert(options.Msg));
			
			options.Bool = result;
			return result;
		},
		
		result: function result() {			
			return options.Bool;
		}

		
	}
	this.Verificat = api;
})();

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言