Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
Lejlek Avatar asked May 14 '11 15:05

Lejlek


People also ask

How do you checked multiple checkbox in jQuery?

$('#CheckAll'). change(function(){ if ($(this).is(":checked")) { $('. checkboxes'). each(function(){ $(this).

How do you check checkbox is enable or disable in jQuery?

$(selector). prop (“disabled”, true | false); This function returns the Boolean value as if the parameter for this prop() function is specified as true then the selected element or checkbox object is disabled else if the parameter is set to false the checkbox object or any other selected element is not disabled.

How do I uncheck a specific checkbox in jQuery?

By using jQuery function prop() you can dynamically add this attribute or if present we can change its value i.e. checked=true to make the checkbox checked and checked=false to mark the checkbox unchecked.


1 Answers

You could do it like this:

$(":checkbox").val(myChoices).filter(":checked").attr("disabled",true);

Here is an example in jsfiddle http://jsfiddle.net/P4VhK/

like image 52
Sang Suantak Avatar answered Sep 22 '22 10:09

Sang Suantak