9

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>

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

Comments

1

See the following code. here i used onchange function.

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

3 Comments

Why repeat $('#inp') ? Use $(this) or this
Yes, we can use that too.sometimes for beginners, it have been a bit tricky to understand $(this). that's why I directly used $('#inp')
I strongly suggest giving beginners best practices from the start
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.