I got some HTML like so of a Bootstrap checkbox. By default the checkbox is on.
<div id="full" class="checkbox">
<label>
<input type="checkbox" checked=""> Include Full Classes
</label>
</div>
I have this jQuery which detects whether the item is checked or non-checked
var full;
$('#full').change(function(){
if(this.checked)
{
full = true;
console.log(full);
} else {
full = false;
console.log(full);
}
});
What I want to achieve is, when the checkbox is selected, it would set full to 1, and if it is unselected, set full to 0.
I performed console.log() to the full variable, and in my output, all I got was false.
I am wondering what I am doing wrong?
This is the thread I am referencing
You will need to give your checkbox its own ID so that you can determine whether it's checked. Right now you are testing whether the div is checked (which isn't possible) - what you want to do instead is check whether the input element is checked!
Working Live Demo:
var full;
$('#checkbox').change(function() {
full = this.checked;
console.log(full);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="full" class="checkbox">
<label>
<input id="checkbox" type="checkbox" checked="">Include Full Classes
</label>
</div>
JSFiddle Example: https://jsfiddle.net/qtczor1q/2/
The output for this.checked is boolean should do the trick
var full;
$('#full').change(function(){
full = this.checked ? 1 : 0 ;
//or using jquery
// full = $(this).is(':checked') ? 1 : 0;
console.log(full);
});
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