Checkbox state needs to show or hide a div

I have a checkbox that, when checked, will display a div. As expected, when it is unchecked, the div will be hidden.

I've got as far as the following code but I need a way to check if the checkbox itself is toggling from check to uncheck!

$(function(){
    if($('#guess_the_score').is(':checked')){
        $("#guess_score_show").toggle();
    }
});

The checkbox has an id of guess_the_score The div to be displayed has an id of guess_score_show

Any help would be appreciated :)

Answers


Use .change event of checkbox and show hide div as shown :

$(function(){
  $('#guess_the_score').change(function(){
     if($(this).is(':checked')){
        $("#guess_score_show").show();
     }
     else{ 
        $("#guess_score_show").hide(); 
     }
  }).change();  //trigger on page load
});

OR

$(function(){
  $('#guess_the_score').change(function(){
      $("#guess_score_show").toggle(this.checked);
  }).change();   //trigger on page load
});

Working DEMO

Working DEMO


You should use change() event, The change event is sent to an element when its value changes.

Use

$(function() {
    $('#guess_the_score').change(function() {
        $("#guess_score_show").toggle(this.checked);
    }).change(); //Trigger on page load
});

$(function() {
  $('#guess_the_score').on('change', function() {
    $("#guess_score_show").toggle(this.checked);
  });
});
#guess_score_show {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Toggle Score
<input id="guess_the_score" type="checkbox" />
<br>
<div id="guess_score_show">Score: 10</div>

Need Your Help

different div positions in IE9 FF and chrome

html css

I have already asked this question but I didn't get a specific answer. so I thought to ask a simplified version of the question

Mapping With Restkit iphone

iphone objective-c xcode mapping restkit

I am trying to map and store a response json data using restkit object mapping. unfortunately i cannot able to map a response data. when i view my database the datas are storing, but i get a crash ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.