带复选框的表单提交

本文介绍了一个实现用户在提交表单前必须至少选中表格中的一项的交互功能,通过选中除表头外任意行的选项来勾选对应行的复选框,提升了用户体验,并使用jq进行表单验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现了:

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" onsubmit="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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值