- 获取单个checkbox选中项(三种写法):
$("input:checkbox:checked").val()
// 或者
$("input:[type='checkbox']:checked").val();
// 或者
$("input:[name='ck']:checked").val();
- 获取多个checkbox选中项:
$('input:checkbox').each(function() {
if ($(this).attr('checked') ==true) {
alert($(this).val());
}
});
- 设置第一个checkbox 为选中值:
$('input:checkbox:first').attr("checked",'checked');
// 或者
$('input:checkbox').eq(0).attr("checked",'true');
- 设置最后一个checkbox为选中值:
$('input:radio:last').attr('checked', 'checked');
// 或者
$('input:radio:last').attr('checked', 'true');
- 根据索引值设置任意一个checkbox为选中值:
$('input:checkbox).eq(索引值).attr('checked', 'true'); // 索引值=0,1,2....
// 或者
$('input:radio').slice(1,2).attr('checked', 'true');
- 选中多个checkbox: 同时选中第1个和第2个的checkbox:
$('input:radio').slice(0,2).attr('checked','true');
- 根据Value值设置checkbox为选中值:
$("input:checkbox[value='1']").attr('checked','true');
- 删除Value=1的checkbox:
$("input:checkbox[value='1']").remove();
- 删除第几个checkbox:
$("input:checkbox").eq(索引值).remove(); //索引值=0,1,2....
// 如删除第3个checkbox:
$("input:checkbox").eq(2).remove();
10.遍历checkbox:
$('input:checkbox').each(function (index, domEle) {
// 写入代码
});
11.全部选中
$('input:checkbox').each(function() {
$(this).attr('checked', true);
});
12.全部取消选择:
$('input:checkbox').each(function () {
$(this).attr('checked',false);
});
13.给 checked 赋值:
$("#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");
示例:必须选则其中一个选项
<div class="right">
<label>
<input type="checkbox" value="1" name="love"/>
</label>
运动
<label>
<input type="checkbox" value="2" name="love"/>
</label>
聊天
<label>
<input type="checkbox" value="3" name="love"/>
</label>
玩游戏
</div>
<script>
$(function() {
$("#submit").on("click", function() {var arr = []
if($(":checkbox:checked").length == 0){
alert("请选择一项爱好");
return false;
}else{
$.each($('input:checkbox:checked'),function(){
arr.push($(this).val())
});
}
console.log(arr)
alert('activityType:' + arr)
})
})
</script>
示例:通过遍历数组给checkbox赋默赋值
<div class="right">
<label>
<input type="checkbox" value="1" name="love"/>
</label>
运动
<label>
<input type="checkbox" value="2" name="love"/>
</label>
聊天
<label>
<input type="checkbox" value="3" name="love"/>
</label>
玩游戏
</div>
<script>
$(function() {
var checklist = ['1', '3']
if (checklist) {
$.each(checklist, function(i,item){
$("input[name='love'][value="+item+"]").attr("checked","checked");
});
}
})
</script>