简体   繁体   中英

Jquery checkbox toggling only on checking unchecking and then checking

I want to show a div on checking a checkbox and hide the div on unchecking the checkbox.This is what I tried.It works only on checking and unchecking and then checking. I am using jquery 3.5.1.

I think there is a problem with this jquery part logic

jquery part

$('.frameopener').on('change', function(){ // on change of state
   if(this.checked) // if changed state is "CHECKED"
    {
       
           var formid=$(this).attr("id");
 
       $("#"+formid+"").click(function() {
   
  $("#" + formid + "form").toggle();
    
});

}
});

php part which dynamically displays checkbox from a loop

echo '
 
  <td>
    <input type="checkbox" class="frameopener" id="'.$checkboxitemsafterstripper[$key].'" ></td><td>'.
   $item.'
  </td>';

Here is the frame which needs to be toggled

foreach( $checkboxitemsafterstripper as $key => $item ){
echo '
<div id="'.$item.'form">';
}

I am not sure why you have use $("#"+formid+"").click(function() {.. there is no need to use this simply get id of checkbox and toggle div.

Demo code :

 $("div[id$=form]").hide() //hide all div whose id end with form $('.frameopener').on('change', function() { // on change of state var formid = $(this).attr("id"); $("#" + formid + "form").toggle(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" class="frameopener" id="12">12 <input type="checkbox" class="frameopener" id="13">13 <input type="checkbox" class="frameopener" id="14">14 <div id="12form">12 div</div> <div id="13form">13 div</div> <div id="14form">14 div</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM