Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Bootstrap 4's custom checkbox state?

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);
})
like image 441
Mojimi Avatar asked Feb 21 '18 20:02

Mojimi


People also ask

How do I get checkbox checked in bootstrap?

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.

How do I customize a checkbox in bootstrap 4?

To create a custom checkbox, wrap a container element, like <div>, with a class of . custom-control and . custom-checkbox around the checkbox.

How do you check checkbox is checked or not?

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);

How can I get the checkbox of a state?

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.


2 Answers

Try this in your event handler:

$(evt.target).is(':checked')
like image 124
combatc2 Avatar answered Oct 19 '22 19:10

combatc2


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.

like image 2
WebDevBooster Avatar answered Oct 19 '22 20:10

WebDevBooster