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>

2
  • and do you preset the value of the checkbox or not? Commented Oct 7, 2019 at 20:44
  • Yes, sure, it is variable. Otherwise the question wouldn't make sense. Commented Oct 7, 2019 at 20:46

3 Answers 3

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>

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

Comments

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>

2 Comments

Oh sure, interesting alternative, I wouldn't think of doing it this way
@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.
-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.

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.