帶複選框的表單提交

實現了:

1.選中除開表頭的任何一行中的任何一項,選中該行復選框,有利於用戶體驗。

2.至少選中表中一項,表單提交。

html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>帶複選框的表單提交</title>
	<script src="../commonJqery/jquery-3.0.0.js" type="text/javascript"></script>
	<style type="text/css">
		table {
			border-collapse: collapse;
		}
		td,th {
			width: 40px;
			height: 100px;
			border:1px solid #000;
		}
		table tbody tr:hover {
			background-color: red;
		}
		table tbody tr:not(:first-child):hover {background-color: #666;
		}
	</style>
</head>
<body>
	<form action="http://www.baidu.com" id="order_shopping" name="order_shopping" method="get" οnsubmit="return checkShopping();">
		<table id="table" class="fl">
			<thead>
				<tr>
					<th>商品名</th>
					<th>單價</th>
					<th>購買數量</th>
					<th><input id="both" type="checkbox" name="both" autocomplete="off"></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>香蕉</td>
					<td>100</td>
					<td>4</td>
					<td>
						<input type="checkbox" name="choice" autocomplete="off">
					</td>
				</tr>
				<tr>
					<td>蘋果</td>
					<td>100</td>
					<td>5</td>
					<td>
						<input type="checkbox" name="choice" autocomplete="off">
					</td>
				</tr>
			</tbody>
		</table>
		<input type="submit" id="add_shopping" value="添加購物車"/>
	</form>
	<p id="msg"></p>
</body>
</html>

js:

<script type="text/javascript">
		$(function(){
			//全選
			$("input[name='both']").click(function(){
			var $isSelected = $(this).is(":checked");
			for(var i = 0;i<$("input[name='choice']").length;i++){
				$("input[name='choice']")[i].checked = $isSelected;
				}
			})

			//選中行選中checkbox
		    $("#table tr").slice(1).each(function(){  
	        var This = this;  
	        $(this).children().click(function(){  
	            $($(This).children()[3]).children().each(function(){  
	                if(this.type=="checkbox"){  
	                    if(!this.checked){  
	                       this.checked = true;  
	                    }else{  
	                        this.checked = false;  
	                    }  
	                }  
	            	});  
	        	});  
	    	}); 
		});
		// 有選中才提交
		function checkShopping(){
			$("#msg").html('');
			var $checkbox = $("input[name='choice']");
			for(var i = 0 ;i<$checkbox.length;i++){
				if(checkObj($checkbox[i])){
					return true;
				}
			}
			if(i==$checkbox.length){
				$("#msg").html('提示:至少選擇1條信息!');
				return false;
			}
		}
		function checkObj(obj){
			if(obj.checked){
				return true;
			}else{
				return false;
			}
		}

</script>


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