Peter C
Peter C

Reputation: 47

bootstrap checkbox changes class when checked

I'm using bootstrap's checkbox and currently looking for a way with jQuery that will allow my checkbox to change class when checked.

<form>
  <div class="checkbox">
    <input type="checkbox" name="checkbox">
    <label for="checkbox">I am not a Robot!</label>
  </div> <!-- //.checkbox -->
</form>

I've tried the following...it's not working as I wanted. Have I made a mistake somewhere?

(document).ready(function() {
  if ($('.checkbox').is(':checked')) {
    $(".checkbox").removeClass('has-error').addClass('has-success'); // checked
  } else {
    $(".checkbox").addClass('has-error'); //unchecked
  }
});

JsFiddle: https://jsfiddle.net/e8d2be7d/

If there's a better way to do this, please comment! Any help will be appreciated. :)

Upvotes: 1

Views: 1799

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

With the current handling, you will be able to add/remove class at the time of document load. However, you need to add/remove class on every click. Hence, you need to bind the function.

$('.checkbox').click(function(){
    if ($(this).is(':checked')) {
        $(this).removeClass('has-error').addClass('has-success'); // checked
    } else {
        $(this).addClass('has-error'); //unchecked
    }
});

Additionally, you will need to update your markup as well with moving class checkbox from div to input. Or you will have to update your selector/code accordingly.

For reference - http://plnkr.co/edit/tkz047HzEya2TkyAFqp0?p=preview

Upvotes: 2

Related Questions