Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Bootstrap checkbox not working with jQuery?

When the input checkbox is checked, I want to append the <div> with a message. But somehow my code doesn't seem to work. Am I missing anything here?

Here's a link to what I've got so far - http://jsbin.com/petewadeho/edit?html,output

<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

  <input id="inp" type="checkbox" data-toggle="toggle" />

  <div id="out"></div>

  <script>
    $('#inp').click(function() {
      if (this.checked) {
        $("#out").append("hey");
      }
    });
  </script>
like image 733
Kemat Rochi Avatar asked Apr 11 '16 08:04

Kemat Rochi


2 Answers

You have used Bootstrap, which is modifying the DOM structure of checkbox element. You need to use .change() event instead of .click():

$('#inp').change(function(){
  if (this.checked) {
      $("#out").append("hey");
  }
}); 

http://jsbin.com/kenekekose/1/edit?html,output

like image 105
Milind Anantwar Avatar answered Oct 23 '22 01:10

Milind Anantwar


See the following code. here i used onchange function.

  <script>
    $('#inp').change(function(){
      if ($('#inp').prop( "checked" )) {
          $("#out").append("hey");
      }
    }); 
  </script>
like image 21
Ataur Rahman Munna Avatar answered Oct 23 '22 03:10

Ataur Rahman Munna