Kemat Rochi
Kemat Rochi

Reputation: 952

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>

Upvotes: 9

Views: 2343

Answers (3)

Tobias Delp
Tobias Delp

Reputation: 53

The click listener you are setting is getting removed when Bootstrap modifies your checkbox.

The following code will add the listener to the body, so it won't get removed with the DOM element, while Bootstrap does its work

$('body').on('click', '#inp', function(){
  //do append
})

Upvotes: 1

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

See the following code. here i used onchange function.

  <script>
    $('#inp').change(function(){
      if ($('#inp').prop( "checked" )) {
          $("#out").append("hey");
      }
    }); 
  </script>

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

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

Upvotes: 9

Related Questions