DCR
DCR

Reputation: 15665

checkboxes not working independently

My js function almost works but the checkboxes are not working quite independently:

UPDATE: I fixed this by adding parent='NULL'; at the end of the function. Could someone explain what's going on???

function detectDiv(obj) {
  var parent = obj.parentElement;
  console.log(parent.id);
  
  
   $('input:checkbox').change(function(){
    if($(this).is(":checked")) {
        $("#"+parent.id).removeClass("grey100");
    } else {        $("#"+parent.id).addClass("grey100");
    }

    parent='NULL';
});

  
   
  
  
}
.grey100 {
    
            opacity: 0.5;
}

img{
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div >
<table>
   <tr>
      <td id='img1' class='grey100'>
<img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br>
<input type="checkbox" onclick="detectDiv(this)" >
      </td>
      <td id='img2' class='grey100'>
<img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br>
<input type="checkbox"  onclick="detectDiv(this)" >
      </td>
      </tr>
 </table>
</div>

Upvotes: 1

Views: 69

Answers (1)

kind user
kind user

Reputation: 41893

I don't see the point to use a separate function with a nested jQuery function to handle it. You can get your expected result using following approach:

$('input:checkbox').change(function() {
  $(this).parent().find('img').toggleClass("grey100");
});
.grey100 {
  opacity: 0.5;
}

img {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <table>
    <tr>
      <td id='img1'>
        <img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br>
        <input type="checkbox">
      </td>
      <td id='img2'>
        <img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br>
        <input type="checkbox">
      </td>
    </tr>
  </table>
</div>

Upvotes: 3

Related Questions