Since I use bootstrap, I looked for this style to make it more user-friendly, since I represent buttons with states true
and false
.
I do it in the following way:
$(function() {
$('#toggle-event').change(function() {
$('#console-event').html('Estado: ' + $(this).prop('checked'))
})
})
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input type="checkbox" id="toggle-event" checked data-toggle="toggle" data-on="Activo" data-off="Inactivo" data-onstyle="success" data-offstyle="danger">
<div id="console-event">Estado: true</div>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
I would like it to have a third state, which is null
. There's a possibility? Or if there is another tool that gives me that option, welcome the suggestion.
A checkbox with 3 states:
Source: Rotating amongst the states
UPDATE:
Using the code above, I've added some styling to the
checkbox
:One option is with CSS Toggle Switch :
I'm going to show you how to create a
checkbox
custom with three states usingCSS
someJavascript
. You can later add Bootstrap styles if you wish.In the first place,
checkbox
styles cannot be assigned to a by default so, instead of him, we will create onelabel
and assign it to himcheckbox
through the attributefor
to be able to assign the styles to said label. Thecheckbox
original will remain hidden.Then, we will have to define the possible states in which the checkbox will be found:
And we will also have to define the possible combinations:
That is, it will always go through the null state before getting one state or another (true/false).
Later, we can use
checkbox.indeterminate = true
it to recreate that the checkbox is in a statenulo
and we will save the next and current state that corresponds to the current state of the checkbox to later be able to perform one action or another. To save the states we will create a couple of attributesdata-
where, in this case, I have callednumero
for the next state andactual
to save the state that it has at the moment of clicking on the checkbox.Lastly, we can use the selectors
:checked
,:indeterminate
,+
and someJavascript
to do the rest. WithJavascript
we will create an event that listens when the checkbox changes state.Full example: