Search code examples
javascriptjqueryonchangeonloadprop

Check if input is checked ONLOAD and ONCHANGE


My javascript skills are subpar so I won't post what I've already tried with jQuery. I can say, however, that I've tried lots of things and nothing worked completely.

The scenario is simple:

I have several containers. All of them with a checkbox inside. The checkboxes have different IDs set dynamically.

This is what I want to accomplish:

  • The container should get the class "active" when the checkbox inside is clicked.
  • Not more than one container should be checked at a time. This is simple using radio buttons, but the point remains: only one "active" item at a time.
  • When the page loads, the script should check for which checkbox is checked, and add the "active" class to its parent accordingly.

Here's the example code:

$(document).on('change', 'input', function() {   
  if (this.checked) {
    $(this).parent('.container').addClass('active');
  } else {
    $(this).parent('.container').removeClass('active');
  }
});
.container {
  background-color: #A9CCE3;
  display: inline-block;
  margin: 4px;
  width: 200px;
  height: 120px;
}

.active {
  background: #2980B9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="container" for="item01">
  <input class="trigger" type="radio" name="grouptrigger" id="item01">
  ITEM
</label>

<label class="container" for="item02">
  <input class="trigger" type="radio" name="grouptrigger" id="item02">
  ITEM
</label>

<label class="container" for="item03">
  <input class="trigger" type="radio" name="grouptrigger" id="item03">
  ITEM
</label>

Update: Posting what I've tried so far for the "change" function. Kinda wants to work but doesn't. I never managed to get a working solution for the "onload" problem.


Solution

  • Simply do this:

    $( 'body' ).on( 'load', function() {
        $( 'input[type="radio"]:checked' ).parent( 'label' ).addClass( 'active' )
    } )
    
    $( 'input[name="trigger"]' ).on( 'change', function() {
        $( '.active' ).removeClass( 'active' );
        $( this ).parent( 'label' ).addClass( 'active' )
    } )
    .container {
        background-color: #A9CCE3;
        display: inline-block;
        margin: 4px;
        width: 200px;
        height: 120px
    }
    .active {
        background: #2980B9
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <label class="container" for="item01">
        <input type="radio" name="trigger" id="item01">
        ITEM 1
    </label>
    <label class="container" for="item02">
        <input type="radio" name="trigger" id="item02">
        ITEM 2
    </label>
    <label class="container active" for="item03">
        <input type="radio" name="trigger" id="item03" checked>
        ITEM 3
    </label>