jquery - control a parent 5 levels back from the checkbox when checkbox is checked -


as can see in html, checkbox buried 5 levels inside class want affect.

$(".icheckbox").click(function() {    if ($(this).is(":checked")) {      $(this).closest(".gallery-item").addclass("active");    } else {      }  });
a.active {    color: red;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <a class="gallery-item" href="#">    <div class="image">      <ul class="gallery-item-controls">        <li>          <label class="check">            <input type="checkbox" class="icheckbox">          </label>        </li>      </ul>    </div>  </a>

what want add .active class gallery-item class when checkbox checked on , remove when off(unchecked). can't find way far jquery , make matters worse, can't control depending on checked attr because checked attr doesn't added when it's checked. weird.

here codepen. if got right, gray area should turn red on , aff checkbox

thanks fellas

you need remove class on else

$(document).ready(function(){   $(".icheckbox").click(function() {     if ($(this).is(":checked")) {       $(this).closest(".gallery-item").addclass("active");     } else {       $(this).closest(".gallery-item").removeclass("active");     }   }); }); 

http://jsbin.com/zikomagike/edit?html,css,js,console,output

if want watch changes, use .change(). triggered if other function changes class , not input.

better add name attribute , use in code: $( "input[name='chkbox']" )

html

<a class="gallery-item" href="#">   <div class="image">     <ul class="gallery-item-controls">       <li>         <label class="check">           <input name="chkbox" type="checkbox" class="icheckbox">         </label>       </li>     </ul>   </div> </a> 

js:

 $(document).ready(function(){       $( "input[name='chkbox']" ).change(function() {         if ($(this).is(":checked")) {           $(this).closest(".gallery-item").addclass("active");         } else {           $(this).closest(".gallery-item").removeclass("active");         }       });     }); 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -