Murtuza Z
Murtuza Z

Reputation: 6017

How do I add indeterminate state in my custom checkbox?

I want to add indeterminate state in my custom checkbox.

Here code

/* The container */
.container {
    display: block;
    position: relative;
    padding-left: 35px;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Hide the browser's default checkbox */
.container input {
    position: absolute;
    opacity: 0;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
    background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
    background-color: #2196F3;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 9px;
    top: 5px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}
<html>
<body>

<h1>Custom Checkbox</h1>
<label class="container">
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

</body>
</html>

Upvotes: 1

Views: 490

Answers (1)

Soolie
Soolie

Reputation: 1820

Regular checkbox is not capable of doing it. You need to use a flag for this. What I would do is to use a counter flag, that is tied to the element:

$(function () {
  $(".check").data("state", 0).addClass("unchecked");
  $(".multi-checkbox").click(function () {
    var states = ["unchecked", "partial", "checked"];
    var curState = $(this).find(".check").data("state");
    curState++;
    $(this).find(".check").removeClass("unchecked partial checked").addClass(states[curState % states.length]).data("state", curState % states.length);
  });
});
.multi-checkbox .check {display: inline-block; vertical-align: top; width: 15px; height: 15px; border: 1px solid #333; margin: 3px;}
.multi-checkbox .check.unchecked {background: #fff;}
.multi-checkbox .check.partial {background: #ccc;}
.multi-checkbox .check.checked {background: #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multi-checkbox">
  <span class="check"></span>
  Check me
</div>

I just wrote this snippet for this answer. Let me know if you have any questions. With font awesome, we can do it in a better way.

Upvotes: 2

Related Questions