+
50
-

jquery和js如何获取checkbox多个选中的值?

请问jquery和js如何获取checkbox多个选中的值?

高手回复

+
0
-

首先看jquey实现多个checkbox选中的值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BFW NEW PAGE</title>

<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">

function getselvalue() {

var id_array = new Array();
$('input[name="checkbox1"]:checked').each(function() {
id_array.push($(this).val()); //向数组中添加元素
});
var idstr = id_array.join(','); //将数组元素连接起来以构建一个字符串
alert(idstr);

}
</script>
</head>
<body>
<div>
<p>
<label for="check1">题目1</label> <input type="checkbox" id="check1" name="checkbox1" value="1" />
</p>
<p>
<label for="check2">题目2</label> <input type="checkbox" id="check2" name="checkbox1" value="2" />
</p>
<p>
<label for="check3">题目3</label> <input type="checkbox" id="check3" name="checkbox1" value="3" />
</p>

<input type="button" id="test"BfwOnclick="getselvalue();" value="提交" />
</div>
</body>
</html>

再看原生js实现多个checkbox选中的值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<script type="text/javascript">

function getselvalue() {


obj = document.getElementsByName("checkbox1");
check_val = [];
for (k in obj) {
if (obj[k].checked)
check_val.push(obj[k].value);
}
alert(check_val);


}
</script>
</head>
<body>
<div>
<p>
<label for="check1">题目1</label> <input type="checkbox" id="check1" name="checkbox1" value="1" />
</p>
<p>
<label for="check2">题目2</label> <input type="checkbox" id="check2" name="checkbox1" value="2" />
</p>
<p>
<label for="check3">题目3</label> <input type="checkbox" id="check3" name="checkbox1" value="3" />
</p>

<input type="button" id="test"BfwOnclick="getselvalue();" value="提交" />
</div>
</body>
</html>


by ppzhuzhu
我知道答案,我要回答