用一个数值保存多选的值

前言

在开发过程中,对于网页中的多选,我们有很多种存储方式,常见的如逗号分隔。下文介绍一种通用设计方式:用一个整数来存储复选框的值。

准备知识 —— 位与运算

位与运算:二进制运算,相同位的两个数字都为1,则为1;若有一个不为1,则为0,如:

1
2
3
4
5
 下方是运算
00101
& 11100
------------
00100

设计

将多项的选项值分别设置为 2 的 n 次方,n 从 0 开始,每多一项,n + 1。即 1,2,4,8…
多选的存储值为各项值之和,如选中了第 1、3 项,则值为:1 + 4 = 5

1
$ hexo server

回显

假设存储的值为 5 ,要使相应的项被勾选,则是循环多项的值,每项与存储值 5 进行 位与运算,如果值与选项本身的值相等,则选中该项;相反地,如果运算值为 0 ,则设置为不选中:

1
2
3
4
5
下方回显
1 & 5 = 1
2 & 5 = 0
4 & 5 = 4
8 & 5 = 0

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkbox Test</title>
</head>
<body>
<form>
<input type="checkbox" name="test" value="1"> 1
<input type="checkbox" name="test" value="2"> 2
<input type="checkbox" name="test" value="4"> 4
<input type="checkbox" name="test" value="8"> 8
</form>
<input type="text" id="result" placeholder="设置要回显的值">
<button id="show">回显</button>
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function () {
$("[name='test']").on("change", function () {
var result = 0;
$("[name='test']:checkbox:checked").each(function(){
result += parseInt($(this).val());
});
$("#result").val(result); });
$("#show").on("click", function () {
var result = parseInt($("#result").val());
$("[name='test']:checkbox").each(function(){
var value = parseInt($(this).val());
if ((result & value) == value) {
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
});
});
</script>
</body>
</html>