魂心

checkbox的选中、全选、返选、获取所有选中的值、所有的值、单选全部时父选中

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-1.11.2.min.js"></script>
<script>
/* 第一种方法
function selectAll() {

if ($("#select-all").is(":checked")) {

$("[name='selected']").prop("checked", true);
} else {

$("[name='selected']").prop("checked", false);
}

} */

/*
*
第二种方法
*/
function selectAll() {

if ($("#select-all").is(":checked")) {//判断一个checkbox多选框是否选中

$("input:checkbox[name='selected']").prop("checked", "checked");

var allValue = queryCheckedValue();
alert(allValue);

} else {

$("input:checkbox[name='selected']").prop("checked", "");
var str = noCheckedValue();
alert(str);

}

}

//获取所有选中checkbox的值

function queryCheckedValue() {

var str = "";

$("input:checkbox[name='selected']:checked").each(function(i) {

var val = $(this).val();
str = str + val + "-";

});

return str;

}

//所有的name为‘selected’的checkbox的值
function noCheckedValue() {

var str = "";
$("input:checkbox[name='selected']").each(function(i) {

var val = $(this).val();
str = str + "-" + val;
});
return str;
}

//判断所有的子checkbox全部选中时,总checkbox选中,否则,反之;
function oneToAll() {

var allChecked = 0;//所有选中checkbox的数量

var all = 0;//所有checkbox的数量

$("input:checkbox[name='selected']").each(function(i) {
all++;
if ($(this).is(":checked")) {
allChecked++;
}

});

if(allChecked==all){//相等时,则所有的checkbox都选中了,否则,反之;

$("#select-all").prop("checked",true);

}else{

$("#select-all").prop("checked",false);

}

}
</script>
</head>
<body>

<table>

<tr>
<td><input type="checkbox" id="select-all"
onclick="selectAll();" /></td>
<td>全选的checkbox</td>
</tr>
<tr>
<td><input type="checkbox" name="selected" value="1" onclick="oneToAll();"/></td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" name="selected" value="2" onclick="oneToAll();"/></td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" name="selected" value="3" onclick="oneToAll();"/></td>
<td>3</td>
</tr>
<tr>
<td><input type="checkbox" name="selected" value="4" onclick="oneToAll();"/></td>
<td>4</td>
</tr>
</tr>
<tr>
<td><input type="checkbox" name="selected" value="5" onclick="oneToAll();"/></td>
<td>5</td>
</tr>
</table>

</body>
</html>

posted on 2017-04-27 11:00  魂心  阅读(15206)  评论(0编辑  收藏  举报