GVKun编程网logo

bootstrap 表格全选、反选、取消操作(bootstraptable全选按钮)

21

如果您对bootstrap表格全选、反选、取消操作和bootstraptable全选按钮感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解bootstrap表格全选、反选、取消操作的各种细节,并对

如果您对bootstrap 表格全选、反选、取消操作bootstraptable全选按钮感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解bootstrap 表格全选、反选、取消操作的各种细节,并对bootstraptable全选按钮进行深入的分析,此外还有关于AJAX 全选、反选删除、ajax全选、全不选、反选、单删/批删、Android RecycleView使用(CheckBox全选、反选、单选)、asp.net GridView控件中模板列CheckBox全选、反选、取消的实用技巧。

本文目录一览:

bootstrap 表格全选、反选、取消操作(bootstraptable全选按钮)

bootstrap 表格全选、反选、取消操作(bootstraptable全选按钮)

先说一下要实现的效果。列表如图所示,点击全选按钮则使所有数据为选中状态;点击取消按钮,则所有数据为未选中状态;点击反选按钮,则把已选中的数据置为未选中,未选中的数据置为选中状态。

代码为:

 

JS代码为:

代码虽然简单,但是却花费了很长时间,主要时间花费在反选功能上。全选和取消操作网上有很多,但是反选功能却始终没有找到。在被逼无奈下,只好从bootstrap的js源码看起。

 

心得:学习框架还是要静下心来研究源代码!

总结

以上是小编为你收集整理的bootstrap 表格全选、反选、取消操作全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://blog.csdn.net/feidie436/article/details/100728756

AJAX 全选、反选删除

AJAX 全选、反选删除

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> JSP+Ajax 添加删除CheckBox实例 example test</TITLE> <Meta NAME="Generator" CONTENT="EditPlus"> <Meta NAME="Author" CONTENT=""> <Meta NAME="Keywords" CONTENT=""> <Meta NAME="Description" CONTENT=""> <script type="text/javascript"> function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } //cody by jarry; var emptyCol="",overCol="#f1f1f1",checkedCol="#F4FFF4"; function getAbsoluteLeft( ob ){ if(!ob){return null;} var obj = ob; var objLeft = obj .offsetLeft; while( obj != null && obj .offsetParent != null && obj .offsetParent.tagName != "BODY" ){ objLeft += obj .offsetParent.offsetLeft; obj = obj .offsetParent; } return objLeft ; } // get absolute TOP position function getAbsolutetop( ob ){ if(!ob){return null;} var obj = ob; var objTop = obj .offsetTop; while( obj != null && obj .offsetParent != null && obj .offsetParent.tagName != "BODY" ){ objTop += obj .offsetParent.offsetTop; obj = obj .offsetParent; } return objTop ; } String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g,"");} function isExist(child,obj){ //obj has element the child; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkBox"){ if(obj.elements[i].value==child)return true; } } return false; } function validateURL(url){ //validateURL if(url.search(/^[A-Za-z0-9 -]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/)!=0){ return false; //}else if(url.substring(0,4)=="www."){ //return false; }else{ return true; } } function countLength(obj){ if(obj==null)return; var dLen = 0,sLen = 0; for(i=0; i< obj.length; i++ ){ if(obj.charCodeAt(i) > "0" && obj.charCodeAt(i) < "128") sLen+=1; else dLen+=2; } totalLen = sLen+dLen; return totalLen; } var strAll=unescape("%u5168%u9009"); var canAll=unescape("%u53D6%u6D88"); function clickchk(obj){ var allcheck=true; for(var i=0;i<obj.elements.length;i++){ var eli = obj.elements[i]; if(eli.tagName.toLowerCase()=="input" && eli.type=="checkBox"){ eli.parentNode.style.backgroundColor = eli.checked ? checkedCol :""; if(eli.checked==false){allcheck=false;} } } obj.elements["check"].value=allcheck?canAll:strAll; } function addSite(obj){ var url=obj.url.value.trim(); if(url.match(/^\s*$/g) || !validateURL(url)){alert("请输入正确网址:如mysite.com");obj.url.focus();return;} if(isExist(url,obj)){alert("你添加的网址已经存在列表中");return;} var list=document.getElementById("list"); var chkBox=document.createElement("input"); chkBox.type="checkBox"; chkBox.onclick=function(){clickchk(obj);}//全部选择后check按钮显示取消; chkBox.value=url; chkBox.name="url_chkBox"; var hr=document.createElement("hr"); hr.size="0";hr.style.borderTop="1px solid gray"; var txt=document.createTextNode(url); var div=document.createElement("div"); div.appendChild(chkBox); div.appendChild(txt); div.style.borderBottom="1px dashed gray"; div.style.padding="5px"; //div.appendChild(hr); //div.style.backgroundColor = "olive"; div.onmouSEOver=function(){ showDelete(this); } div.onmouSEOut=function(){ hideDelete(this); } list.appendChild(div); //end add; //如果已经添加了多选框则去掉禁用; if(obj.check.disabled==true){ obj.check.disabled=false; obj.recheck.disabled = false; obj.remove.disabled=false; } return false; } function checkall(obj){//全选or取消全选; var chk=obj.elements["check"]; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkBox"){ if(chk.value==strAll){//check all checkBox input; obj.elements[i].checked=true; obj.elements[i].parentNode.style.backgroundColor = checkedCol; }else{ obj.elements[i].checked=false; obj.elements[i].parentNode.style.backgroundColor = emptyCol; } } } if($('list').childNodes.length<=1)return; chk.value=chk.value==canAll?strAll:canAll; //更改全选/取消的显示; } function reverseCheck(obj){ var chk=obj.elements["check"]; for(var i=0;i<obj.elements.length;i++){ if(obj.elements[i].tagName.toLowerCase()=="input" && obj.elements[i].type=="checkBox"){ obj.elements[i].checked = obj.elements[i].checked ? false : true; } clickchk(obj); } } function del(list,obj){ //删除list的内容 var candel=false; var i=list.childNodes.length; var end = -1; while( i > end ){ //如果存在child var s=list.childNodes[i]; if(typeof(s)!="undefined" && s.tagName){ try{ //如果child的类型不为空; var tgname = s.tagName.toupperCase(); if(tgname != "DIV" || s.childNodes.length <=0 )return; //子集是div且还有子集 var s1 = s.childNodes[0]; if( s1.type.toLowerCase() =="checkBox" && s1.checked==true ){ //如果该子集里的checkBox选中,那么删除改子集(div); candel = true; list.removeChild(s); } }catch(ex){ //alert(ex.toString()); } } i--; } if(candel==false){alert("请选择你要删除的选项")} isdisabledButton(); } function isdisabledButton(){ var objform=document.sitelist; var list=$("list"); var hasDivChild = false; if(list.childNodes.length>0 ){ for(var i=0;i<list.childNodes.length;i++){ var s=list.childNodes[i]; if( typeof(s)!="undefined" && s.tagName) { if(s.tagName.toupperCase()=="DIV") hasDivChild = true; } } } objform.check.disabled= hasDivChild?false:true; objform.recheck.disabled= hasDivChild?false:true; objform.check.value=strAll; objform.remove.disabled= hasDivChild?false:true; } function delSingle(objparent,objdel,objchild){ objparent.removeChild(objchild); objdel.style.display="none"; // isdisabledButton(); } function editSingle(objparent,objedit,objchild){ function makeLink(text,tag){ var temobj = document.createElement(tag); temobj.style.marginLeft="5px"; temobj.style.marginRight="5px"; temobj.style.textdecoration="underline";temobj.style.cursor="pointer"; temobj.appendChild( document.createTextNode(text) ); return temobj; } try{ var secondChild = objchild.childNodes[1]; var url = secondChild; var urlStr = url.nodeValue ;//? url.nodeValue : url.toString() ; if(urlStr==null || urlStr.trim=="")return; var editorPanel = document.createElement("span"); objchild.removeChild(url); var editor = document.createElement("input"); editor.type="text"; //var maxLen = parseInt(objparent.style.width) - 250; var maxLen = 50; var thisLen = parseInt( countLength(urlStr) ); editor.size = maxLen > thisLen ? thisLen : maxLen; editor.value = urlStr; editor.select(); editor.onmouSEOver=function(){this.select();} var update = makeLink("update","font");update.title="更新"; update.onclick=function(){ //updateContens(); var newvalue = editor.value; if(newvalue.trim() == ""){editor.focus();return;} objchild.removeChild(objchild.childNodes[1]); objchild.appendChild(document.createTextNode(newvalue)); } var cancle = makeLink("cancle","font");cancle.title="取消"; cancle.onclick=function(){ objchild.removeChild(objchild.childNodes[1]); objchild.appendChild(url); } //add to editorPanel; editorPanel.style.fontSize="11px"; editorPanel.style.color="blue"; editorPanel.appendChild(editor); editorPanel.appendChild(update); editorPanel.appendChild(document.createTextNode("|")); editorPanel.appendChild(cancle); //add to objchild; objchild.appendChild(editorPanel); }catch(ex){ alert(ex.toString()); }finally{ // } } var currentDiv; function showDelete(self){ self.style.backgroundColor = overCol; currentDiv = self; var theid = "del_icon"; if(!$(theid)){ var delDiv=document.createElement("div"); delDiv.id=theid; var d=delDiv; d.style.textAlign="center";d.style.fontSize="11px"; var edit = document.createElement("span"); edit.title="编辑此条";edit.style.textdecoration="underline"; edit.onclick=function(){ editSingle(currentDiv.parentNode,this.parentNode,currentDiv); } var del = document.createElement("span"); del.title="删除此条";del.style.textdecoration="underline"; del.onclick=function(){ delSingle(currentDiv.parentNode,currentDiv); } edit.appendChild(document.createTextNode("edit")); d.appendChild(edit); d.appendChild(document.createTextNode(" | ")); del.appendChild(document.createTextNode("delete")); d.appendChild(del); d.style.width="80px"; d.style.lineHeight="20px"; d.style.color="blue"; // d.style.zIndex="-10"; // d.style.backgroundColor="green"; document.body.appendChild(d); $(theid).onmouSEOver=function(){ currentDiv.style.backgroundColor = overCol; this.style.display=""; //mouSEOndeleteDiv=true; } // $(theid).style.cursor="pointer"; } if($(theid)){ $(theid).style.display=""; var l= getAbsoluteLeft(self) + self.offsetWidth - 80; var t= getAbsolutetop(self) + 5; var scrollT = self.parentNode.scrollTop;//减去出现滚动条的高度; var t= getAbsolutetop(self) + 5 - scrollT; $(theid).style.position="absolute"; $(theid).style.left = l+"px"; $(theid).style.top = t+"px"; } } function hideDelete(self){ var theid = "del_icon"; if( $(theid) ){ self.style.backgroundColor = self.childNodes[0].checked?checkedCol:emptyCol; $(theid).style.display="none"; } } </script> </HEAD> <BODY> <style> .drag{position:absolute;width:600px; background-color:#f1f1f1; filter:alpha(opacity=100); -moz-opacity:1.0; opacity:1.0; } .da{width:100%;background-color:gray;cursor:move;font-size:14px;vertical-align:middle;line-height:30px} .max_min_btn{float:right;color:red;cursor:pointer;font-size:9pt;width:50px;line-height:30px;text-align:center;} #list{border-top:2px ridge #9A9898;border-left:2px ridge #9A9898;border-bottom:1px solid #D4D0C8;border-right:1px solid #D4D0C8;background:white;width:578px;height:350px;margin:10px;overflow:auto} .shadowBottom{margin-left:6px;height:5px;background:gray;font-size:0px;line-height:0px;filter:alpha(opacity=55);-moz-opacity:0.55;opacity:0.55;} </style> <pre> 本例是采用JSP + Ajax + 文本来演示多选、全选,添加、删除、更新checkBox多选框的效果。 本例充分展现了利用JavaScript控制HTML DOM以及利用XML http 传递数据,利用JSP操作文本的效果。 1,JavaScript 用来控制页面内容的现实与增删效果; 2,JSP作为后台,对文本进行读取、写入、更新等操作; 3,文本格式是用来存储数据的,数据编码UTF-8;<br>4,本例子在win32,Red hat Linux 9下 jdk1.5,Tomcat 5.0,Apache 2.5下调试通过,同时兼容Firefox 1.0,Opera 8.0,IE6。 <br>在线说明文档 <a href="http://jiarry.blogchina.com/5599587.html">http://jiarry.blogchina.com/5599587.html</a><br>静态页面演示地址:<A href="http://jarryli.googlepages.com/checkBox_test.html">http://jarryli.googlepages.com/checkBox_test.html</A> (详细的说明,随后补充)<BR>源文件下载地址:<A href="http://jarryli.googlepages.com/checkBox.rar">http://jarryli.googlepages.com/checkBox.rar</A> <br> 另外之前做的<br> PHP+Ajax 发帖程序实例:<a href="http://jiarry.blogchina.com/5555296.html">http://jiarry.blogchina.com/5555296.html</a> 源码下载:<a href="http://jarryli.googlepages.com/post_ajax.rar">http://jarryli.googlepages.com/post_ajax.rar</a><br> JSP登录证码无刷新提示:<a href="http://jiarry.blogchina.com/5287654.html">http://jiarry.blogchina.com/5287654.html</a> 源码下载:<a href="http://jarryli.googlepages.com/imgValidate.rar">http://jarryli.googlepages.com/imgValidate.rar</a><br> <br> <divrel="drag" id="siteMainDarg"onMouseDown="dargit(this,event);"> <div><spanid="max_min"><font>2</font>CLOSE</span>&nbsp;&nbsp;拖拽区</div> <div id="sitelistDiv" > <form name="sitelist" onSubmit="return addSite(this);"><br clear="all"> &nbsp;&nbsp;http:// <INPUT TYPE="text" size="30" NAME="url" onmouSEOver="this.focus()"> <INPUT TYPE="button" NAME="add" value="添加网址至列表" onClick="addSite(this.form)"> <div id="list"> <div onMouSEOver="showDelete(this);" onmouSEOut="hideDelete(this);"https://www.jb51.cc/tag/ott/" target="_blank">ottom:1px dashed gray"><input type=checkBox value="example.com" name="url_chkBox" onClick="clickchk(this.form)">example1.com </div> <div onMouSEOver="showDelete(this);" onMouSEOut="hideDelete(this);"https://www.jb51.cc/tag/ott/" target="_blank">ottom:1px dashed gray"><input type=checkBox value="example.com" name="url_chkBox" onClick="clickchk(this.form)">example2.com </div> </div> &nbsp;&nbsp;<INPUT TYPE="button" NAME="check" value="全选" disabled onClick="checkall(this.form)">&nbsp;&nbsp;<input type="button" value="反选" name="recheck" disabled onclick="reverseCheck(this.form)">&nbsp;&nbsp;<INPUT TYPE="button" NAME="remove" disabled value="删除" onClick="del($('list'),this.form)"><br><br> </form> </div> <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom">&nbsp;</div> </div><br><br><br> Cody by JarryLi@gmail.com; <br> copyRight?Jarry,All right reserved!<br> 本例仅供个人参考,引用请保留版权信息。谢谢! <br> homepage:<a href="http://jiarry.126.com">jiarry.126.com</a><br> Blog:<a href="http://jiarry.blogchina.com">http://jiarry.blogchina.com</a> <script> //页面加载时初始化 function init(l,f){ var list=l; f.check.disabled=list.childNodes.length>1?false:true; f.recheck.disabled=list.childNodes.length>1?false:true; f.check.value=strAll; f.remove.disabled=list.childNodes.length>1?false:true; } window.onload=function(){ init($("list"),document.sitelist); } activeCookie = true; if(document.cookie==null){ //alert("cookie没有开启!"); activeCookie = false; } function getCookie(name) { if( !activeCookie ) return; var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charat(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function setCookie(name,value) { if( !activeCookie ) return; var expdate = new Date(); expdate.setTime(expdate.getTime() + (365*24*120)); document.cookie=""+ name + "=" + value +";expires="+ expdate.toGMTString(); } var theLeft = getCookie("siteMainDargLeft")!=null ? getCookie("siteMainDargLeft") : 10; var thetop = getCookie("siteMainDargTop")!=null ? getCookie("siteMainDargTop") : 10; var listDivdisplay = getCookie("sitelistDivdisplay")!=null ? getCookie("sitelistDivdisplay") : ""; $("siteMainDarg").style.top = thetop; $("siteMainDarg").style.left = theLeft; $("sitelistDiv").style.display = listDivdisplay; //cookie end; //////////////////////// var d_width = 550; var d_height = 30; var ey=0,ex=0,lx=0,ly=0,canDrg=false,thiso=null;// var x,y,rw,rh; var divs=document.getElementsByTagName("div"); for (var i=0;i<divs.length;i++){ if(divs[i].getAttribute("rel")=="drag"){ divs[i].onmousemove=function(){ thismove(this);//实时得到当前对象与鼠标的值以判断拖动及关闭区域; } } } function thismove(o){ rw = parseInt(x)-parseInt(getAbsoluteLeft(o)); rh = parseInt(y)-parseInt(getAbsolutetop(o)); } function dargit(o,e){ thiso = o; canDrg = true; if(!document.all){ lx = e.clientX; ly = e.clientY; }else{ lx = event.x; ly = event.y; } try{//设置渐变色; if(rh<=d_height && rw<d_width &&rh>0){//设定在拖动区域 if(document.all)thiso.filters.Alpha.opacity=80; else thiso.style.MozOpacity=80/100; } }catch(e){ } st(o); } document.onmousemove = function(e){ if(!document.all){ x = e.clientX; y = e.clientY; }else{ x = event.x; y = event.y; } if(canDrg){ if(rh<=d_height && rw<d_width &&rh>0){//如果要设定拖动区域可以作判断 var ofsx = x - lx; thiso.style.left = (parseInt(thiso.style.left) + ofsx) +"px"; lx = x; var ofsy = y - ly; thiso.style.top = (parseInt(thiso.style.top) + ofsy) +"px"; ly = y; }else{ canDrg=false; } } } document.onmouseup=function(){ canDrg=false;//拖拽变量设为false try{ if(document.all)thiso.filters.Alpha.opacity=100; else thiso.style.MozOpacity=100; }catch(e){} if(document.all && thiso != null){ thiso.releaseCapture(); thiso = null; } } function st(o){ if(rh <= d_height && rw >= d_width){ canDrg=false; showHide($("sitelistDiv")); } } function showHide(obj,self){ obj.style.display = obj.style.display=="none"?"":"none"; //$("del_icon").display="none"; var icon = "1"; var text = "OPEN"; if(obj.style.display==""){ icon = "2"; text = "CLOSE"; } $("max_min").childNodes[0].innerHTML = icon; $("max_min").childNodes[1].nodeValue = text; } window.onunload = function(){ setCookie("siteMainDargLeft",getAbsoluteLeft( $("siteMainDarg") ) ); setCookie("siteMainDargTop",getAbsolutetop( $("siteMainDarg") ) ); setCookie("sitelistDivdisplay",$("sitelistDiv").style.display ); } </script> </BODY> </HTML>

ajax全选、全不选、反选、单删/批删

ajax全选、全不选、反选、单删/批删

show.php

<meta charset="utf-8">
<?php
//链接数据库
$link = mysqli_connect(''127.0.0.1'',''root'',''root'',''mone'');
//设置字符集
mysqli_query($link,''set names utf8'');


//接收当前页
$page = empty($_GET[''page''])?1:$_GET[''page''];
//求出总条数
$sql = "select * from user";
$res = mysqli_query($link,$sql);
$count = mysqli_num_rows($res);
//每页显示多少条
$length = 3;
//求出总页数
$num_page = ceil($count/$length);
//偏移量
$limit = ($page-1)*$length;
//查询
$sql2 = "select * from user limit $limit,$length";
$res2 = mysqli_query($link,$sql2);
while($a=mysqli_fetch_assoc($res2)){
    $data[''data''][] = $a;
}


$data[''home_page''] = 1;
$data[''prev_page''] = $page-1<1?1:$page-1;
$data[''next_page''] = $page+1>$num_page?$num_page:$page+1;
$data[''last_page''] = $num_page;

?>
<table>
    <tr>
        <th>选择</th>
        <th>ID</th>
        <th>用户名</th>
        <th>密码</th>
        <th>性别</th>
        <th>年龄</th>
        <th>班级</th>
        <th>手机</th>
        <th>编辑</th>
    </tr>
    <div id="main">
    <?php foreach($data[''data''] as $k=>$v){ ?>
    <tr id="<?php echo $v[''user_id''];?>">
        <td><input type="checkbox" name="check" value="<?php echo $v[''user_id''];?>"></td>
        <td><?php echo $v[''user_id''];?></td>
        <td><?php echo $v[''username''];?></td>
        <td><?php echo $v[''pwd''];?></td>
        <td><?php echo $v[''sex''];?></td>
        <td><?php echo $v[''age''];?></td>
        <td><?php echo $v[''class_name''];?></td>
        <td><?php echo $v[''phone''];?></td>
        <td>
            <a href="">修改</a>
        </td>
    </tr>
    <?php } ?>
</div>
</table>

<button onclick="fun1()">全选</button>
<button onclick="fun2()">全不选</button>
<button onclick="fun3()">反选</button>
<button onclick="fun4()">单删/批删</button>
<script>
    

    function fun1(){
        var check = document.getElementsByName(''check'');
        for(var i=0;i<check.length;i++){
            if(check[i].checked==false){
                check[i].checked=true;
            }
        }
    }

    function fun2(){
        var check = document.getElementsByName(''check'');
        for(var i=0;i<check.length;i++){
            if(check[i].checked==true){
                check[i].checked=false;
            }
        }
    }

    function fun3(){
        var check = document.getElementsByName(''check'');
        for(var i=0;i<check.length;i++){
            if(check[i].checked==true){
                check[i].checked=false;
            }else{
                check[i].checked=true;
            }
        }
    }

    function fun4(){
        var arr = document.getElementsByName(''check'');
        var ar = [];
        for(var i=0;i<arr.length;i++){
            if(arr[i].checked==true){
                ar.push(arr[i].value);
            }
        }

        var id = ar.toLocaleString();
        if(id==''''){
            alert(''请先选择一项'');
            return false;
        }else{
            //ajax请求
            var ajax = new XMLHttpRequest();
            ajax.open("get","delete.php?id="+id);
            ajax.send();
            ajax.onreadystatechange=function(){
                if(ajax.readyState==4 && ajax.status==200){
                    //alert(ajax.responseText);
                    //成功
                    if(ajax.responseText==1){

                        for(var i=0;i<ar.length;i++){
                            var tr=document.getElementById(ar[i]);
                            tr.remove();
                        }

                    }
                }
            }
        }
    }
</script>

 

 

delete.php

<?php
//接收传值
$id = $_GET[''id''];
//链接数据库
$link = mysqli_connect(''127.0.0.1'',''root'',''root'',''mone'');
//设置字符集
mysqli_query($link,''set names utf8'');
//拼接sql
$sql = "DELETE FROM user WHERE user_id in ($id)";
if(mysqli_query($link,$sql)){
    echo 1;
}else{
    echo 2;
}

 

Android RecycleView使用(CheckBox全选、反选、单选)

Android RecycleView使用(CheckBox全选、反选、单选)

本文实例为大家分享了CheckBox全选、反选、单选的具体代码,供大家参考,具体内容如下

MainActiivity

package com.bwie.day06;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.linearlayoutmanager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.bwie.day06.myadapter.MyAdapter;

public class MainActivity extends AppCompatActivity {

  private MyAdapter myAdapter;
  private linearlayoutmanager linearlayoutmanager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //初始化控件
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    //在加载数据之前配置
    linearlayoutmanager = new linearlayoutmanager(this);
    recyclerView.setLayoutManager(linearlayoutmanager);
    //创建一个适配器
    myAdapter = new MyAdapter();
    recyclerView.setAdapter(myAdapter);


  }

  public void btnAll(View view) {
    myAdapter.All();
  }

  public void btnner(View view) {
    myAdapter.neverall();
  }
}

Adapter

package com.bwie.day06.myadapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.bwie.day06.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
  //这个是checkBox的Hashmap集合
  private final HashMap<Integer,Boolean> map;
  //这个是数据集合
  private final ArrayList<String> list;

  public MyAdapter() {
    map = new HashMap<>();
    list = new ArrayList<>();
    for (int i = 0; i < 30; i++) {
      //添加30条数据
      list.add("这是条目" + i);
      map.put(i,false);
    }

  }

  /**
   * 全选
   */
  public void All() {
    Set<Map.Entry<Integer,Boolean>> entries = map.entrySet();
    boolean shouldall = false;
    for (Map.Entry<Integer,Boolean> entry : entries) {
      Boolean value = entry.getValue();
      if (!value) {
        shouldall = true;
        break;
      }
    }
    for (Map.Entry<Integer,Boolean> entry : entries) {
      entry.setValue(shouldall);
    }
    notifyDataSetChanged();
  }

  /**
   * 反选
   */
  public void neverall() {
    Set<Map.Entry<Integer,Boolean>> entries = map.entrySet();
    for (Map.Entry<Integer,Boolean> entry : entries) {
      entry.setValue(!entry.getValue());
    }
    notifyDataSetChanged();
  }

  /**
   * 单选
   *
   * @param postion
   */
  public void singlesel(int postion) {
    Set<Map.Entry<Integer,Boolean> entry : entries) {
      entry.setValue(false);
    }
    map.put(postion,true);
    notifyDataSetChanged();
  }

  //这里主要初始化布局控件
  @Override
  public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
    RecyclerView.LayoutManager layoutManager = ((RecyclerView) parent).getLayoutManager();
    //初始化布局文件
    View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.check,parent,false);
    return new MyViewHolder(inflate);
  }

  @Override
  public void onBindViewHolder(final MyViewHolder holder,final int position) {
    //放入集合中的值
    holder.txt.setText(list.get(position));
    holder.checkBox.setChecked(map.get(position));
    holder.checkBox.setonClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        map.put(position,!map.get(position));
        //刷新适配器
        notifyDataSetChanged();
        //单选
//        singlesel(position);

      }
    });

  }

  @Override
  public int getItemCount() {
    return list.size();
  }

  public class MyViewHolder extends RecyclerView.ViewHolder {
    View itemView;
    private TextView txt;
    private CheckBox checkBox;

    //初始化控件
    public MyViewHolder(View itemView) {
      super(itemView);
      this.itemView = itemView;
      txt = (TextView) itemView.findViewById(R.id.txt);
      checkBox = (CheckBox) itemView.findViewById(R.id.cBox);
    }
  }
}

main.xml

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">

  <Button
    android:onClick="btnAll"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="全选" />

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="反选"
    android:onClick="btnner"/>

</LinearLayout>

<android.support.v7.widget.RecyclerView
  android:id="@+id/recyclerview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

Check.xml

<CheckBox
  android:id="@+id/cBox"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />


<TextView
  android:text="dfdfdfdf"
  android:id="@+id/txt"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="20sp" />

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

asp.net GridView控件中模板列CheckBox全选、反选、取消

asp.net GridView控件中模板列CheckBox全选、反选、取消

using System; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Collections; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 

public partial class Demo18 : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (Page.IsPostBack == false) 
{ 
BindData(); 
} 
} 

public void BindData() 
{ 
string strSql = "select UserID,C_Name,E_Name,UpdataDate,isDY from Demo_User "; 
DataTable dt = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, CommandType.Text, strSql, null).Tables[0]; 

GridView.DataSource = dt; 
GridView.DataKeyNames = new string[] { "UserID" };//主键 
GridView.DataBind(); 
} 

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e) 
{ 
GridView.PageIndex = e.NewPageIndex; 
BindData(); 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
CheckBoxAll.Checked = false; 
CheckBox1.Checked = false; 
for (int i = 0; i <= GridView.Rows.Count - 1; i++) 
{ 
CheckBox CheckBox = (CheckBox)GridView.Rows[i].FindControl("CheckBox"); 
CheckBox.Checked = false; 
} 

} 

protected void Button2_Click(object sender, EventArgs e) 
{ 
for (int i = 0; i <= GridView.Rows.Count - 1; i++) 
{ 
CheckBox CheckBox = (CheckBox)GridView.Rows[i].FindControl("CheckBox"); 
if (CheckBox.Checked == true) 
{ 
string strSql = "Update Demo_User set UpdataDate=@UpdataDate where UserID=@UserID "; 
SqlParameter[] para = { 
new SqlParameter("@UpdataDate", DateTime.Now), 
new SqlParameter("@UserID", GridView.DataKeys[i].Value), 
}; 
SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING, CommandType.Text, strSql, para); 
} 
} 
CheckBoxAll.Checked = false; 
CheckBox1.Checked = false; 
BindData(); 

} 

protected void CheckBoxAll_CheckedChanged(object sender, EventArgs e) 
{ 
for (int i = 0; i <= GridView.Rows.Count - 1; i++) 
{ 
CheckBox CheckBox = (CheckBox)GridView.Rows[i].FindControl("CheckBox"); 
if (CheckBoxAll.Checked == true) 
{ 
CheckBox.Checked = true; 
} 
else 
{ 
CheckBox.Checked = false; 
} 
} 
CheckBox1.Checked = false; 

} 

protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 
{ 
for (int i = 0; i <= GridView.Rows.Count - 1; i++) 
{ 
CheckBox CheckBox = (CheckBox)GridView.Rows[i].FindControl("CheckBox"); 
if (CheckBox.Checked == false) 
{ 
CheckBox.Checked = true; 
} 
else 
{ 
CheckBox.Checked = false; 
} 
} 
CheckBoxAll.Checked = false; 
} 
} 

<table align="center" bgcolor="#c0de98" border="0" cellpadding="0" cellspacing="1" width="99%"> 
<tr> 
<th colspan="2"> 
GridView演示</th> 
</tr> 
<tr> 
<td colspan="2"> 
<asp:GridView ID="GridView" runat="server" Width="100%" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView_PageIndexChanging" PageSize="12" > 
<Columns> 
<asp:TemplateField HeaderText="选择"> 
<ItemTemplate> 
<asp:CheckBox ID="CheckBox" runat="server" /> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" /> 
<asp:BoundField DataField="C_Name" HeaderText="中文名字" ReadOnly="True" /> 
<asp:BoundField DataField="E_Name" HeaderText="英文名字" ReadOnly="True" /> 
<asp:BoundField DataField="UpdataDate" HeaderText="更新时间" /> 
</Columns> 
<RowStyle HorizontalAlign="Center" /> 
<PagerStyle HorizontalAlign="Right" /> 
</asp:GridView> 
</td> 
</tr> 

<tr> 
<td > 
<asp:CheckBox ID="CheckBoxAll" runat="server" Text="全选" Width="80px" AutoPostBack="True" OnCheckedChanged="CheckBoxAll_CheckedChanged" /> 
<asp:CheckBox ID="CheckBox1" runat="server" Text="反选" Width="80px" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged" /> 
<asp:Button ID="Button1" runat="server" Text="取 消" CssOnClick="Button1_Click"/> 
<asp:Button ID="Button2" runat="server" Text="更新时间" CssOnClick="Button2_Click"/></td> 
</tr> 
</table>
登录后复制

asp.net gridview控件中模板列checkbox全选、反选、取消

更多asp.net GridView控件中模板列CheckBox全选、反选、取消相关文章请关注PHP中文网!

今天关于bootstrap 表格全选、反选、取消操作bootstraptable全选按钮的讲解已经结束,谢谢您的阅读,如果想了解更多关于AJAX 全选、反选删除、ajax全选、全不选、反选、单删/批删、Android RecycleView使用(CheckBox全选、反选、单选)、asp.net GridView控件中模板列CheckBox全选、反选、取消的相关知识,请在本站搜索。

本文标签: