In their documentation here : http://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1
It's never mentioned how to properly use the custom checkboxes, using the inspector it doesn't seem like any class is added, and the value is always "on".
It's also not mentioned how do I change their state via html or javascript.
JsFiddle : https://jsfiddle.net/2n40w13k/1/
Js :
$('.custom-control-input').on('change', evt => {
console.log(evt.target.value);
})
Example Explained form-check-input to style checkboxes properly inside the . form-check container. Use the checked attribute if you want the checkbox to be checked by default.
To create a custom checkbox, wrap a container element, like <div>, with a class of . custom-control and . custom-checkbox around the checkbox.
To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);
To get the state of a checkbox, you follow these steps: First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
Try this in your event handler:
$(evt.target).is(':checked')
That is done by using the :checked
, :active
and :focus
pseudo-classes.
So, when you click a custom checkbox (or radio button), the :checked
pseudo-class is applied to it. When you click it again, that pseudo-class is removed. And that's what you target with css to change appearance.
The same is true for JavaScript/jQuery. You'd need to add/remove the corresponding pseudo-class (:checked
) via JavaScript/jQuery if you wanted to control it that way.
The last snippet of my answer here:
https://stackoverflow.com/a/48401949/8270343
explains it in further detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With