Chain Trap
Chain Trap

Reputation: 130

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.

I tried the following code but the results does nothing.

#1. hasAttribute():

if ($('input[type=checkbox]').hasAttribute("disabled")) {
  $(this).closest('.chkbox').addClass("is-disabled");
}

#2. is():

if ($('input[type=checkbox]').is("[disabled]")) {
  $(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
  $(this).closest('.chkbox').addClass("is-disabled");
}

#3. prop():

if ($('input[type=checkbox]').prop("disabled", true)) {
  $(this).closest('.chkbox').addClass("is-disabled");
}

So then I think the problem is on the line:

$(this).closest('.chkbox').addClass("is-disabled");

Any idea?

Thanks.

Upvotes: 0

Views: 1209

Answers (2)

roberrrt-s
roberrrt-s

Reputation: 8210

You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.

This code should work as you desire.

$(function() {

  // Grab all inputs with the type checkbox.
  var input = $('input[type=checkbox]')

  // Check for each of the input fields (i, el stands for index, element)
  input.each(function(i, el) {
    // Does it have the attribute disabled?
    if(el.hasAttribute('disabled')) {
      // Add the class 'is-disabled'
      $(el).closest('.chkbox').addClass('is-disabled')
    }
  })

  $('input[type=checkbox]').change(function(){
    if ($(this).is(":checked")) {
        $(this).closest('.chkbox').addClass("is-checked");
    } else {
        $(this).closest('.chkbox').removeClass("is-checked");
    }
  });
});

Upvotes: 0

Behzad Shirani
Behzad Shirani

Reputation: 137

You can use :disabled selector

see here

Upvotes: 2

Related Questions