我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
这可能会帮助某人。
HTML5
<input id="check_box" type="checkbox" onclick="handleOnClick()">
JavaScript。
function handleOnClick(){
if($("#check_box").prop('checked'))
{
console.log("current state: checked");
}
else
{
console.log("current state: unchecked");
}
}
其他回答
这是用jQuery检查和取消检查复选框的正确方法,因为它是跨平台标准的,并且允许表单转发。
$('.myCheckBox').each(function(){ this.checked = true; });
$('.myCheckBox').each(function(){ this.checked = false; });
通过这样做,您将使用JavaScript标准来检查和取消选中复选框,因此任何正确实现checkbox元素的“checked”属性的浏览器都将完美地运行此代码。这应该是所有主要的浏览器,但我无法在Internet Explorer 9之前进行测试。
问题(jQuery 1.6):
一旦用户单击复选框,该复选框将停止响应“选中”的属性更改。
下面是一个复选框属性在有人单击复选框后无法完成任务的示例(这在Chrome中发生)。
不停摆弄
解决方案:
通过在DOM元素上使用JavaScript的“checked”属性,我们能够直接解决问题,而不是试图操纵DOM来完成我们希望它做的事情。
不停摆弄
该插件将更改jQuery选择的任何元素的checked属性,并在所有情况下成功选中和取消选中复选框。因此,虽然这看起来像是一个负担过重的解决方案,但它将使您的网站的用户体验更好,并有助于防止用户受挫。
(function( $ ) {
$.fn.checked = function(value) {
if(value === true || value === false) {
// Set the value of the checkbox
$(this).each(function(){ this.checked = value; });
}
else if(value === undefined || value === 'toggle') {
// Toggle the checkbox
$(this).each(function(){ this.checked = !this.checked; });
}
return this;
};
})( jQuery );
或者,如果您不想使用插件,可以使用以下代码片段:
// Check
$(':checkbox').prop('checked', true);
// Un-check
$(':checkbox').prop('checked', false);
// Toggle
$(':checkbox').prop('checked', function (i, value) {
return !value;
});
你可以试试这个:
$('input[name="activity[task_state]"]').val("specify the value you want to check ")
假设问题是。。。
如何选中按值设置的复选框?
请记住,在典型的复选框集中,所有输入标记都具有相同的名称,它们的不同之处在于属性值:集合中的每个输入都没有ID。
Xian的答案可以用更具体的选择器扩展,使用以下代码行:
$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
这是完整的答案使用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
});
下面是如何选中多个复选框的代码和演示。。。
http://jsfiddle.net/tamilmani/z8TTt/
$("#check").on("click", function () {
var chk = document.getElementById('check').checked;
var arr = document.getElementsByTagName("input");
if (chk) {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = true;
}
} else {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = false;
}
}
});