JS----checked----checked选中和未选中的获取

47 篇文章 1 订阅
28 篇文章 0 订阅




全选、全不选、反选功能


html代码

<form action="" id="oForm" name="myForm">
        <input type="checkbox" name="hobby" id="basket" value="basket">篮球<Br>
        <input type="checkbox" name="hobby" id="zuqiu" value="zuqiu" >足球<Br>
        <input type="checkbox" name="hobby" id="paiqiu" value="paiqiu">排球<Br>
        <input type="checkbox" name="hobby" id="wqiu" value="wqiu">网球<Br>
        <input type="checkbox" name="hobby" id="biqiu" value="biqiu">壁球<Br>
        <input type="checkbox" name="hobby" id="bpq" value="bpq">乒乓球<Br>
        <input type="checkbox" name="hobby" id="ymq" value="ymq">羽毛球<Br>
        <input type="button" name="all" id="all" value='全选' οnclick="setVal(1)">
        <input type="button" name="allNo" id="allNo" value='全不选' οnclick="setVal(0)">
        <input type="button" name="noCheck" id="noCheck" value='反选' οnclick="setVal(-1)">
  </form>




JS代码

function setVal(iNum){
        var aForm = document.getElementById("myForm");
        var aArr = aForm.hobby;   
        for(var i=0;i<aArr.length;i++){        
            if( iNum<0 ){
                aArr[i].checked = !aArr[i].checked;   
            }else{
                aArr[i].checked = iNum;
            }           
        }
    }



设置选中

下边两种写法没有任何区别 只是少了些代码而已
<input id="cb1" type="checkbox" checked />
<input id="cb2" type="checkbox" checked="checked" />


jquery赋值checked的几种写法:
所有的jquery版本都可以这样赋值:
// $("#cb1").attr("checked","checked");
// $("#cb1").attr("checked",true);


jquery1.6+:prop的4种赋值:
// $("#cb1").prop("checked",true);//很简单就不说了哦
// $("#cb1").prop({checked:true}); //map键值对
// $("#cb1").prop("checked",function(){
return true;//函数返回true或false
});
//$("#cb1").prop("checked","checked");



为什么input checkbox有 checked='checked'还是没选中
如果用jQuery1.6+来写的话:
建议使用
$(element).prop('checked', true/false);
而不是
$(element).attr('checked', true/false);
其实也就相当于要使用:
element.checked = true/false;
而并不是
element.setAttribute('checked', true/false/'checked');





jquery判断checked的三种方法

.attr('checked'):   //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'):    //所有版本:true/false//别忘记冒号哦




jQuery获取未选中的checkbox

 $('input[type=checkbox]').not("input:checked");  




jQuery获取选中的checkbox

$('input[type=checkbox]:checked');






jquery官网checked的用法

http://api.jquery.com/checked-selector/





DataTable翻页checked部分代码

内容太多需要勾选时,我们需要做翻页,但是翻页要记录之前的页面勾选了哪些,需要借助input来记录。html代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="com.data.web.view.function" prefix="cf"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>
<body>
<link rel="stylesheet" href="/assets/js/dataTables/dataTables.responsive.min.css"></link>
<div id="page-wrapper">
    <div id="page-inner">
	<div class="col-md-12">
			<h1 class="page-head-line">  参考文献      <button id="btnSave" type="button" class="btn btn-success pull-right" data-loading-text="Saving...">保 存</button></h1>
	        <form class="form-inline col-sm-11" id="search_form">
					<input class="form-control" type="hidden" name="plate" value="8">
			</form>
	</div>
			
		<input class="form-control" type="hidden" id='checkList' >
		<div class="row">
			<div class="col-md-12">
				<div class="panel panel-default">
					<div class="panel-heading">参考文献列表</div>
					<div class="panel-body">
						<div class="table-responsive">
							<table
								class="table table-striped table-bordered responsive table-hover"
								id="table" cellspacing="0" width="100%">
								<thead>
									<tr>
										<th width="8%" class="min-mobile-l">期刊名</th>
										<th width="20%" class="desktop">标题</th>
										<th width="10%" class="min-mobile-l">作者</th>
										<th width="10%" class="min-mobile-l">摘要</th>
										<th width="10%" class="min-mobile-l">引用</th>
									</tr>
								</thead>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
</div>
</div>
</body>
</html>
 <!-- /. WRAPPER  -->
    <!-- JS Scripts-->
    <!-- jQuery Js -->
    <script src="/assets/js/jquery-1.10.2.js"></script>
    <!-- Bootstrap Js -->
    <script src="/assets/js/bootstrap.min.js"></script>
    <!-- Metis Menu Js -->
    <script src="/assets/js/jquery.metisMenu.js"></script>
      <!-- CUSTOM SCRIPTS -->
    <script src="/assets/js/custom.js"></script>

    
    <!-- Morris Chart Js 
    <script src="assets/js/morris/raphael-2.1.0.min.js"></script>
    <script src="assets/js/morris/morris.js"></script>-->
    <!-- Custom Js 
    <script src="assets/js/custom-scripts.js"></script>-->
     <!-- DATA TABLE SCRIPTS -->
    <script src="/assets/js/dataTables/jquery.dataTables.js"></script>
    <script src="/assets/js/dataTables/dataTables.bootstrap.js"></script>
    <script src="/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
    <script src="/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>
<script type="text/javascript">
  $(function(){
	  
		var checkedIdsOld = "<c:forEach items="${ancestry.documents}" var="item">${ item.id }|</c:forEach>";
		$("#checkList").val(checkedIdsOld);
	  
	  refreshTable();
	  bindCheckListChange();
        $('#btnSave').click(function(){
        	$(this).button('loading');
        	var allValue = $("#checkList").val();
        	allValue = allValue.substring(0, allValue.length - 1);
        	allValue = allValue.replace(/[ ]/g, "");
        	var checkedIds = allValue.split("|");
        	console.log(checkedIds);
        	 $.postJSON('/docAssociate', 
        			 checkedIds,
        	 	function(res){
        	 		$('#btnSave').button('reset');
        	 		location.href = '/test}'
        	 		if(!res.code){
        	 			alert('保存失败');
        	 		}
        	 	}
      	 	);
        });  
    });
  
  
  

  
  function bindCheckListChange() {
	  $('#table').on('change','.checkbox',function(){
			var allValue = $("#checkList").val();
			if (typeof($(this).attr("checked")) == "undefined") {
				//改变前是 未选中,则变为选中,把值增加到checkList中
				$(this).attr("checked", 'true');
				if (!contains(allValue, $(this).attr("value"), false)) {
					allValue += $(this).attr("value") + "|";
					$("#checkList").val(allValue);
					console.log(allValue);
				}
			} else {
				//改变前是选中,则变为未选中,把值从checkList中删除
				$(this).removeAttr("checked");
				if (contains(allValue, $(this).attr("value"), false)) {
					var rstr = $(this).attr("value") + "|";
					allValue = allValue.replace(rstr, "");
					$("#checkList").val(allValue);
					console.log(allValue);
				}
			}
	  })
	}
  
  
	function refreshTable() {
		$('#table')
				.DataTable(
						{
							responsive : true,
							lengthChange : false,
							serverSide : true,//分页,取数据等等的都放到服务端去
							stateSave : true,
							searching : false,
							processing : true,//载入数据的时候是否显示“载入中”
							bDestroy : true,
							pageLength : 2,//首次加载的数据条数
							ordering : false,//排序操作在服务端进行,所以可以关了。
							language : {
								processing : "载入中",//处理页面数据的时候的显示
								paginate : {//分页的样式文本内容。
									previous : "上一页",
									next : "下一页",
									first : "第一页",
									last : "最后一页"
								},
								zeroRecords : "没有内容",//table tbody内容为空时,tbody的内容。
								//下面三者构成了总体的左下角的内容。
								info : "第 _PAGE_/_PAGES_页 共 _TOTAL_条记录",//左下角的信息显示,大写的词为关键字。
								infoEmpty : "第 _PAGE_/_PAGES_页 共 _TOTAL_条记录",//筛选为空时左下角的显示。
								infoFiltered : ""//筛选之后的左下角筛选提示(另一个是分页信息显示,在上面的info中已经设置,所以可以不显示),
							},
							"columnDefs" : [ {
								"defaultContent" : "",
								"targets" : "_all"
							} ],
							"ajax" : {//类似jquery的ajax参数,基本都可以用。
								type : "post",//后台指定了方式,默认get,外加datatable默认构造的参数很长,有可能超过get的最大长度。
								url : "/referenceDocument/listData",
								dataSrc : "data",//默认data,也可以写其他的,格式化table的时候取里面的数据
								data : function(d) {//d 是原始的发送给服务器的数据,默认很长。
									var param = {};//因为服务端排序,可以新建一个参数对象
									param.start = d.start;//开始的序号
									param.length = d.length;//要取的数据的
									var formData = $("#search_form")
											.serializeArray();//把form里面的数据序列化成数组
									formData.forEach(function(e) {
										param[e.name] = e.value;
									});
									return param;//自定义需要传递的参数。
								}
							},
							"columns" : [
									{
										"data" : "author",
										"class" : "text-center"
									},
									{
										"data" : "title",
										"class" : "text-center",

									},
									{
										"data" : "name",
										"class" : "text-center",

									},
									{
										"data" : "summary",
										"class" : "text-center",
									},
									{
										
										 "class": "text-center",
									      "render": function(data, type, row, position) {
									  		var allValue = $("#checkList").val();
									    	allValue = allValue.substring(0, allValue.length - 1);
									    	allValue = allValue.replace(/[ ]/g, "");
									    	var checkedIds = allValue.split("|");
									        return '<input type="checkbox" class="checkbox"  value="' + row.id + '" ' + (checkedIds && checkedIds.indexOf(row.id) > -1 ? 'checked="checked"' : '') + '">';
									      }
									}
									 ]

						});
	}
	
	
	/**
	*string:原始字符串
	*substr:子字符串
	*isIgnoreCase:忽略大小写
	*/
	function contains(string, substr, isIgnoreCase) {
		if (isIgnoreCase) {
			string = string.toLowerCase();
			substr = substr.toLowerCase();
		}
		var startChar = substr.substring(0, 1);
		var strLen = substr.length;
		for (var j = 0; j < string.length - strLen + 1; j++) {
			if (string.charAt(j) == startChar) //如果匹配起始字符,开始查找
			{
				if (string.substring(j, j + strLen) == substr) //如果从j开始的字符与str匹配,那ok
				{
					return true;
				}
			}
		}
		return false;
	}


  /**
     * like $.getJSON, Load JSON-encoded data from the server using a POST HTTP
     * request.
     */
  $.postJSON = function(url, data, fnSuccess, fnError) {
    $.ajax({
      url: url,
      type: "POST",
      dataType: "json",
      cache: false,
      contentType: "application/json",
      data: JSON.stringify(data),
      success: function(result) {
        fnSuccess && (fnSuccess(result) || 1) || (typeof result.code != 'undefined' && !result.code && tip(result.error || '更新失败...'));
      },
      error: function(err) {
        if (err.status == 401) {
          return tip(err.status + ' ' + err.statusText + ', 当前会话已失效,请去新窗口 <a target="_blank" href="/login?from=' + encodeURIComponent(location.href) + '">登陆</a> 后继续操作!', 60000);
        }
        fnError && (fnError.apply($, Array.prototype.slice.call(arguments)) || 1) || tip(err.status + ' ' + err.statusText);
      }
    });
  };
</script>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小凡vip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值