Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting boolean variable when checkbox is clicked

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

like image 761
theGreenCabbage Avatar asked May 25 '26 06:05

theGreenCabbage


2 Answers

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/

like image 146
Maximillian Laumeister Avatar answered May 27 '26 19:05

Maximillian Laumeister


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);
});
like image 27
joyBlanks Avatar answered May 27 '26 19:05

joyBlanks