我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
我无法通过以下方式实现:
$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');
true和false都会选中该复选框。对我有用的是:
$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', ''); // For unchecking
其他回答
这是完整的答案使用jQuery
我测试了它,它100%工作:D
// when the button (select_unit_button) is clicked it returns all the checed checkboxes values
$("#select_unit_button").on("click", function(e){
var arr = [];
$(':checkbox:checked').each(function(i){
arr[i] = $(this).val(); // u can get id or anything else
});
//console.log(arr); // u can test it using this in google chrome
});
如果您使用ASP.NET MVC,生成许多复选框,然后必须使用JavaScript选择/取消选择所有选项,您可以执行以下操作。
HTML
@foreach (var item in Model)
{
@Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}
JavaScript
function SelectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', true);
});
}
function UnselectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', false);
});
}
当您选中以下复选框时:;
$('.className').attr('checked', 'checked')
这可能还不够。您还应调用以下函数:;
$('.className').prop('checked', 'true')
尤其是在删除复选框选中属性时。
整体而言:
$("#checkAll").click(function(){
$(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});
假设问题是。。。
如何选中按值设置的复选框?
请记住,在典型的复选框集中,所有输入标记都具有相同的名称,它们的不同之处在于属性值:集合中的每个输入都没有ID。
Xian的答案可以用更具体的选择器扩展,使用以下代码行:
$("input.myclass[name='myname'][value='the_value']").prop("checked", true);