使用JQuery获取被选中的checkbox的value值

时间:2021-04-16

  以下为使用JQuery获取input checkbox被选中的值代码:

<html>
<head>
<meta charset="gbk">
<!-- 引入JQuery -->
<script src="jquery-1.3.1.js" type="text/javascript"></script>
</head>

<body>
<input type="checkbox" value="橘子" name="check">橘子1</input>
<input type="checkbox" value="香蕉" name="check">香蕉1</input>
<input type="checkbox" value="西瓜" name="check">西瓜1</input>
<input type="checkbox" value="芒果" name="check">芒果1</input>
<input type="checkbox" value="葡萄" name="check">葡萄1</input>

<input type="button" value="方法1" id="b1">
<input type="button" value="方法2" id="b2">

</body>

<script>
//方法1
$("#b1").click(function(){
//$('input:checkbox:checked') 等同于 $('input[type=checkbox]:checked')
//意思是选择被选中的checkbox
$.each($('input:checkbox:checked'),function(){
window.alert("你选了:"+
$('input[type=checkbox]:checked').length+"个,其中有:"+$(this).val());
});
});

//方法2
$("#b2").click(function(){
$.each($('input:checkbox'),function(){
if(this.checked){
window.alert("你选了:"+
$('input[type=checkbox]:checked').length+"个,其中有:"+$(this).val());
}
});
});
</script>
</html>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章