Disable javascript unchecked checkbox

Asked

Viewed 92 times

2

I need to disable all checkboxes that are not selected/marked. I tried with the following code:

$('input[type=checkbox]').change(function(){
   if($(this).prop("checked", false)){
      $('input[type="checkbox"]:checked', false).prop("disabled", true);   
   }
});

But it’s wrong because it’s not working.

I need a strength to make it work.

Thanks in advance.

1 answer

4


You can do it like this:

$('input[type=checkbox]').each(function() {
  if (!this.checked) this.disabled = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" checked />

Or in one line:

$('input[type=checkbox]:not(:checked)').prop('disabled', true);

The .change() will run only when the value changes, and only in the one that changes.

  • 1

    Thanks @Sergio. Worked perfectly!

  • @Brunooliveira!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.