How to check and disable several checkboxes with jQuery?
I have the following HTML code:
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
...
<input type="checkbox" value="30" />
and the user has checked some of the boxes in a previous visit, and开发者_如何学运维 those values are stored in a variable (gets its value from the server):
myChoices = ["1", "5", "12"]
It is easy to check all checkboxes that have a value in myChoices, it can be done with:
$.(':checkbox').val(myChoices)
But I want to both check and disable these boxes. I do have a solution like follows:
$(':checkbox').each(function()
{if ($.inArray(this.value, myChoices) != -1)
{this.checked=true; this.disabled=true;}
})
It works fine, but I was simply wondering whether there is a simpler solution, something similar to val(), which is so elegant.
Thanks.
You could do it like this:
$(":checkbox").val(myChoices).filter(":checked").attr("disabled",true);
Here is an example in jsfiddle http://jsfiddle.net/P4VhK/
精彩评论