Samto
Samto

Reputation: 101

How to handle initial state and change of checkbox using jQuery?

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>

Upvotes: 1

Views: 268

Answers (3)

mrSerious
mrSerious

Reputation: 84

[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.

Upvotes: -1

Taplar
Taplar

Reputation: 24965

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>

Upvotes: 1

tom
tom

Reputation: 10601

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>

Upvotes: 1

Related Questions