开发者

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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜