1

I need to show/hide div based on checkbox value by jquery:

  1. when webpage is loaded and
  2. when checkbox value is changed (on click/on change)

I found few ways how to solve these problems separately, but does exists a simple way how to handle both group of events at once?

Example (change):

$(document).ready(function(){
    $('#checkbox1').change(function(){
        if(this.checked)
            $('#autoUpdate').show();
        else
            $('#autoUpdate').hide();
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-check-input" type="checkbox" id="checkbox1" checked>

<div id="autoUpdate" class="autoUpdate">
    Example
</div>
Samto
  • 77
  • 5

3 Answers3

1

You can fire the event when the page is loaded:

$('#checkbox1').change();

$(document).ready(function(){
    $('#checkbox1').change(function(){
      console.log('fired');
      if(this.checked)
        $('#autoUpdate').show();
      else
        $('#autoUpdate').hide();
    });
    $('#checkbox1').change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-check-input" type="checkbox" id="checkbox1" checked>

<div id="autoUpdate" class="autoUpdate">
    Example
</div>
kmgt
  • 5,826
  • 4
  • 18
  • 41
1

Just to offer an alternative, if your elements are siblings, you could do the same logic with CSS, applying a display none to the sibling if a previous sibling is not checked.

#checkbox1:not(:checked) ~ #autoUpdate {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-check-input" type="checkbox" id="checkbox1" checked>

<div id="autoUpdate" class="autoUpdate">
  Example
</div>
Taplar
  • 24,246
  • 4
  • 18
  • 33
  • Oh sure, interesting alternative, I wouldn't think of doing it this way – Samto Oct 07 '19 at 21:18
  • @TomasKujal keep in mind it can be considered brittle, given that they need to be siblings. However, depending upon your UI, this might be all you need. – Taplar Oct 07 '19 at 21:19
-1

[I misread the question, my bad.]

Use .on() to bind your function to multiple events.

$('#element').on('click change', function(e) { // e.type is the type of event fired });

Look at this answer for more details.

mrSerious
  • 39
  • 1
  • 5