用jq实现购物车复选框的交互功能

动态生成复选框与AJAX交互
本文介绍了一种使用JavaScript动态生成复选框的方法,并实现与AJAX的交互来更新状态。通过监听主复选框和子复选框的状态变化,确保两者的一致性。同时展示了如何通过AJAX向后端传递数组形式的数据。

动态生成多行复选框

var count1=0;
var count2=0;

var t1 = $("#fun1");	 
$.getJSON("servlet/FindState",null,function(k){
$(k).each(function(i,n){
		count1++;
		t1.append("<tr><td align='left' style='padding-left:20px'><input class='xx1' type='checkbox'/>"+n.state+"</td></tr>");
	});	
});

var t2 = $("#fun2");
$.getJSON("servlet/FindType",null,function(k){
	
	$(k).each(function(i,n){
		count2++;
		t2.append("<tr><td align='left' style='padding-left:20px'><input class='xx2' type='checkbox'/>"+n.TYPE+"</td></tr>");
	});
});

点击主复选框,子复选框被点亮

$("#label1").click(function(){
	if($(this).prop("checked")){
		$(".xx1").prop("checked",true);
	}else{
		$(".xx1").prop("checked",false);
	}	
});
$("#label2").click(function(){
	if($(this).prop("checked")){
		$(".xx2").prop("checked",true);
	}else{
		$(".xx2").prop("checked",false);
	}	
});

当子复选框全部选中时,主复选框被选中;当子复选框都为选中时,主复选框取消选中;

var n11=0;

var arry1=new Array();
$("#fun1").on("click",".xx1,#label1",function(){
	
	if($(this).prop("checked"))
	{
	    arry1.splice(0,arry1.length);//清空数组
		//arry1.push($(this).parent().text());
		$(".xx1").each(function(i){
			   if($(this).prop("checked")){
				n11++;
				arry1.push($(this).parent().text());
			}
		});
		console.log(arry1);
		console.log(arry1.length);
		$.ajax({  
		    url : "servlet/Changestate",
		    traditional: true,
		    data : {"arry1" : arry1},  
		    type : "post"  
		});
		if(n11==count1)
		{
			//console.log(count1);//外面取不到值,这里取到值的未解之谜
			$("#label1").prop("checked",true);
			n11=0;
		}
		n11=0;
	}else{
		$("#label1").prop("checked",false);
	}	
});
var n12=0;

$("#fun2").on("click",".xx2,#label2",function(){
	
	if($(this).prop("checked"))
	{
		$(".xx2").each(function(){
			   if($(this).prop("checked")){
				n12++;
				//console.log(n12);
			}
		});
		if(n12==count2)
		{
			//console.log(count2);//外面取不到值,这里取到值的未解之谜
			$("#label2").prop("checked",true);
			n12=0;
		}
		n12=0;
	}else{
		$("#label2").prop("checked",false);
	}	
});


如何使用ajax向severlet传送一个数组类型的数据

$.ajax({  
		    url : "servlet/Changestate",
		    traditional: true,
		    data : {"arry1" : arry1},  
		    type : "post"  
		});




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值