How to disable checkbox with jquery?

I was looking for more time with him, but it does not work, I want the checkbox to be disabled, the user did not check and can check it if there is any condition. Ok, now I tried to disable them. I am using jquery 2.1.3

<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U01" />Banana <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U02" />Orange <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U03" />Apple <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U04" />Candy 
 $(window).load(function () { $('#chk').prop('disabled', true); }); 
+6
source share
3 answers

id must be unique. You cannot have four flags with the same identifier.

You can try other selectors to select the entire range of .checkbox1 , for example .checkbox1 (by class), input[type="checkbox"] (by tag / attribute). After correcting the identifiers, you can even try #chk1, #chk2, #chk3, #chk4 .

The snippet below uses the class name chk instead of id 'chk'. He also uses attr to set the attribute, although it works for me using prop .

 $(window).load(function() { $('.chk').attr('disabled', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" class="chk" name="check[]" value="U01" />Banana <input type="checkbox" class="chk" name="check[]" value="U02" />Orange <input type="checkbox" class="chk" name="check[]" value="U03" />Apple <input type="checkbox" class="chk" name="check[]" value="U04" />Candy 
+10
source

You have already changed the identifier, but you can also put the class in the same attribute as:

 <input type="checkbox" class="checkbox1 chk" name="check[]" value="U01" />Banana 

Then you can use jQuery to disable or check the checkbox depending on your needs.

To disable:

 $(function () { $('.chk').prop('disabled', true); }); 

To perform a “preliminary check”:

 $(function () { $('.chk').prop('checked', true); }); 

You can change the selector to match the identifiers or classes of even elements and change the properties between true or false to suit your needs.

+1
source

HTML:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U01" />Banana <input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U02" />Orange <input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U03" />Apple <input type="checkbox" class="checkbox1" class="chk" name="check[]" value="U04" />Candy 

Javascript / jquery

 $(function() { $("input.checkbox1").prop("disabled", true); }); 
+1
source

Source: https://habr.com/ru/post/989079/


All Articles